TL;DR: This post explains how to keep PostgreSQL manageable under high-volume telemetry by replacing a single ever-growing table with declarative table partitioning. You will learn how to use
PARTITION BY RANGEto route time-series data into monthly child tables, keep indexes small, retire old data withoutDELETEbloat, and automate partition maintenance with Node.js. Partitioning does not spread load across servers; it organizes data inside one instance.
Key Takeaways
- On a single table with hundreds of millions of rows, every extra index adds write cost and grows past what fits in memory, which hurts high-volume inserts.
- Stop using standard
DELETEqueries to purge old logs, which causes MVCC "dead tuples" and table bloat that requires resource-heavyVACUUMprocesses to clean up. - Implement declarative table partitioning using
PARTITION BY RANGE (created_at)on a parent table to automatically route incoming telemetry into smaller child tables. - Define time-bound child partitions using
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')so you can retire old data by detaching and dropping a whole table instead of deleting individual rows. - Create future partitions ahead of time with a scheduled job (a Node.js worker or the
pg_partmanextension), because an insert with no matching partition fails.
You launched a new application and made the smart choice to track user behavior. To do this, you created a simple database table to store telemetry: automated event data sent from your app to your server, such as button clicks, page views, error logs, or GPS coordinates.
At first, everything works well. You insert thousands of rows a day into your PostgreSQL database without trouble. Six months later the application has grown, and you are inserting millions of rows per day.
Now the database is struggling. Queries over recent data slow down, autovacuum runs constantly, and cleanup jobs compete with live traffic.
-- The simple table that worked fine on day one,
-- but is now bottlenecking your database on day 180.
CREATE TABLE app_telemetry (
id SERIAL PRIMARY KEY,
event_name VARCHAR(255) NOT NULL,
user_id INT NOT NULL,
event_data JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Without a suitable index, this scans the whole table, all 500 million rows.
SELECT COUNT(*) FROM app_telemetry
WHERE created_at >= NOW() - INTERVAL '1 day';
When searching for a solution, the most common advice is to add an index (a fast lookup structure, similar to a book's index). That is the right first step, but on a table with 500 million rows each index is itself huge: building it takes a long time, every insert must update every index, and once the indexes no longer fit in memory, writes and reads both slow down.
Next, you might try deleting old data by running a query to remove logs older than 30 days. Surprisingly, this often makes things worse. In PostgreSQL, deleting large amounts of data causes Table Bloat. Thanks to Multi-Version Concurrency Control (MVCC), Postgres doesn't immediately erase deleted rows; it merely marks them as "dead tuples" and hides them until a background process called VACUUM reclaims the space.
At this point, you might consider migrating to a specialized time-series database. That can be the right call at very large scale, but it means new infrastructure and a data migration.
Before that, it is worth trying a built-in PostgreSQL feature that changes how the data is stored: declarative table partitioning. In this guide, we will break down what partitioning is, how to set it up in PostgreSQL, and how to automate the maintenance process using Node.js.
What is Table Partitioning?
Imagine you run an office, and you store every single piece of paperwork in one giant cardboard box. Whenever your boss asks for yesterday's invoices, you have to sift through the entire box, pushing aside papers from three years ago just to find what you need.
Adding an index is like making a master list of where every paper is located. It helps you find things faster, but every time you file a new paper, you have to rewrite the massive list.
Table Partitioning is like buying a filing cabinet with multiple drawers. You label one drawer "January 2026," another "February 2026," and so on.
- When you need a document from January, you only open the January drawer.
- When you insert a new document, you drop it straight into the current month's drawer.
- When the documents in a drawer get too old, you pick up the whole drawer and throw it away, with no sorting or erasing required.
In PostgreSQL, we create a "Parent" table that acts like the filing cabinet. It doesn't actually store any data itself. Instead, it routes incoming data into smaller "Child" tables (the drawers) based on a predefined rule, most commonly the created_at timestamp.
Production Note: Partitioning is ideal for time-series data, event logging, auditing, and high-volume transactions where you regularly query recent data and eventually delete or archive older records.
Let's look at how to set this up using standard SQL commands.
-- Step 1: Create the "Parent" table.
-- Notice the "PARTITION BY RANGE" command.
-- We are telling Postgres to divide the data based on the 'created_at' column.
CREATE TABLE partitioned_telemetry (
id BIGINT GENERATED ALWAYS AS IDENTITY,
event_name VARCHAR(255) NOT NULL,
user_id INT NOT NULL,
event_data JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
-- A primary key on a partitioned table must include the partition key
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
-- Step 2: Create the "Child" tables (the partitions).
-- Bounds are interpreted in the session time zone, so run this with
-- the time zone set to UTC to get UTC month boundaries.
-- The lower bound is inclusive and the upper bound is exclusive.
CREATE TABLE telemetry_2026_01 PARTITION OF partitioned_telemetry
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
-- We create another table for February 2026.
CREATE TABLE telemetry_2026_02 PARTITION OF partitioned_telemetry
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
When your Node.js application inserts a row into partitioned_telemetry, PostgreSQL looks at the created_at timestamp. If the date is January 15th, it routes that row into telemetry_2026_01. Inserts and queries against the parent table do not need to change. Do keep created_at in the WHERE clause of your queries, because that is what lets PostgreSQL skip irrelevant partitions (partition pruning).
Automating Partition Creation with Node.js
There is a catch to PostgreSQL partitioning: the database does not automatically create new partitions for future months. If March 1st arrives and the March partition does not exist, every insert for March fails with a no partition of relation "partitioned_telemetry" found for row error. Your app keeps running, but that telemetry is lost unless you retry it. A DEFAULT partition can catch stray rows, but rows that land there must be moved before you can create the matching partition, so treat it as a safety net, not a plan.
We need a way to automatically create next month's partition before the current month ends. The established option is the pg_partman extension, which creates future partitions and applies retention for you, and is available on many managed PostgreSQL services. If you cannot install extensions, a small Node.js worker does the same job, and that is what we build here.
We will use Node.js along with the pg (PostgreSQL client) library and node-cron (a task scheduler) to automate table generation.
First, let's install our dependencies in our Node.js project:
# Initialize a new Node.js project
npm init -y
# Install the PostgreSQL client and a cron job scheduler
npm install pg node-cron dotenv
Now, let's write a script that runs every day, checks if next month's partition exists, and creates it if it doesn't. We'll use a PostgreSQL connection Pool because the process stays running between scheduled runs.
// partition-manager.js
require('dotenv').config();
const { Pool } = require('pg');
const cron = require('node-cron');
// Setup the connection pool to our PostgreSQL database
const dbPool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
async function createNextMonthPartition() {
try {
// 1. Figure out what the next month is, in UTC.
// Using local-time dates with toISOString() shifts the date by a day
// in time zones ahead of UTC (for example IST), so stay in UTC throughout.
const today = new Date();
const nextMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + 1, 1));
const monthAfterNext = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() + 2, 1));
// Format bounds as explicit UTC timestamps for PostgreSQL
const startDateStr = `${nextMonth.toISOString().split('T')[0]} 00:00:00+00`;
const endDateStr = `${monthAfterNext.toISOString().split('T')[0]} 00:00:00+00`;
// Format the table name (e.g., telemetry_2026_04)
const yearStr = nextMonth.getUTCFullYear();
const monthStr = String(nextMonth.getUTCMonth() + 1).padStart(2, '0');
const tableName = `telemetry_${yearStr}_${monthStr}`;
console.log(`Checking partition: ${tableName}...`);
// 2. Create the partition if it does not exist.
// DDL cannot use bind parameters; these values are computed above, never user input.
const createQuery = `
CREATE TABLE IF NOT EXISTS ${tableName}
PARTITION OF partitioned_telemetry
FOR VALUES FROM ('${startDateStr}') TO ('${endDateStr}');
`;
await dbPool.query(createQuery);
console.log(`Successfully ensured partition ${tableName} exists.`);
} catch (error) {
// Alert on this: a missing partition means failed inserts next month
console.error('Failed to create partition:', error);
}
}
// 3. Schedule this task to run every day at 2:00 AM
// Cron format: 'Minute Hour Day Month DayOfWeek'
cron.schedule('0 2 * * *', async () => {
console.log('Running daily partition maintenance...');
await createNextMonthPartition();
});
// Run once immediately on startup just to be safe
console.log('Partition manager running.');
createNextMonthPartition();
Because the job runs daily and looks a month ahead, a single failed run is not a problem; the next run creates the partition. Add an alert on failures anyway, and run only one instance of the worker so two schedulers do not race each other.
Mastering Indexes on Partitioned Tables
Now that our data is separated into smaller chunks, we still want indexes for the queries we run most often.
Since PostgreSQL 11, creating an index on a partitioned parent table creates a matching index on every existing partition, and on any partition created or attached later, including the ones our Node.js script creates.
Beginner Tip: Always index the column you use most often in your
WHEREclauses. For telemetry data, this is almost always the timestamp or the user ID.
-- Creating an index on the parent table.
-- We frequently search for a specific user's recent events,
-- so the equality column (user_id) goes first and the range column second.
CREATE INDEX idx_telemetry_user_created
ON partitioned_telemetry (user_id, created_at);
-- PostgreSQL will automatically cascade this index onto:
-- telemetry_2026_01
-- telemetry_2026_02
-- And the new tables our Node.js cron job creates!
Each partition's index is only as large as that month's data, so the indexes being written to (the current month's) are more likely to stay in memory. Reads that filter on created_at touch only the matching partitions. Note that CREATE INDEX CONCURRENTLY cannot be run on the parent table; for an existing large table, the PostgreSQL docs describe creating the index ON ONLY the parent, building each partition's index concurrently, and attaching them.
Archiving: The Smart Way to Delete Data
We have solved the insertion speed and the query speed. But what about database storage space? Telemetry data builds up fast, and we likely need to delete data older than 90 days.
Remember that a large DELETE leaves dead tuples behind and creates heavy VACUUM work? Partitioning offers an alternative: detaching and dropping partitions.
When you want to throw away old data, you don't run a DELETE query row-by-row. Instead, you disconnect (detach) the entire month's table from the parent table, and then either export it to cheaper storage (like Amazon S3) or drop the whole table.
Dropping a table removes its files, so the space is returned to the operating system without any VACUUM work. The catch is locking: a plain DETACH PARTITION or DROP TABLE on a partition takes an ACCESS EXCLUSIVE lock on the parent, which briefly blocks inserts and queries and waits behind long-running queries. On PostgreSQL 14 and later, DETACH PARTITION ... CONCURRENTLY needs only a SHARE UPDATE EXCLUSIVE lock on the parent. It must run outside a transaction block and is not allowed when the table has a DEFAULT partition, which is another reason to avoid relying on one.
Let's build a final Node.js worker that drops partitions older than 3 months. It lists the existing partitions instead of guessing a single name, so a missed run does not leave old partitions behind. It runs once and exits, which suits an OS-level cron job or a scheduled container task.
// archiver.js
require('dotenv').config();
const { Client } = require('pg');
async function dropOldPartitions() {
const dbClient = new Client({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
try {
await dbClient.connect();
// Keep the current month plus the previous 3 full months (UTC)
const now = new Date();
const cutoff = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 3, 1));
const cutoffName = `telemetry_${cutoff.getUTCFullYear()}_${String(cutoff.getUTCMonth() + 1).padStart(2, '0')}`;
// List the partitions currently attached to the parent table
const { rows } = await dbClient.query(`
SELECT c.relname AS name
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
WHERE i.inhparent = 'partitioned_telemetry'::regclass
`);
// telemetry_YYYY_MM names sort chronologically as strings
const expired = rows
.map((row) => row.name)
.filter((name) => /^telemetry_\d{4}_\d{2}$/.test(name) && name < cutoffName);
for (const name of expired) {
console.log(`Detaching and dropping partition ${name}`);
// CONCURRENTLY (PostgreSQL 14+) avoids blocking the parent; it cannot run in a transaction
await dbClient.query(
`ALTER TABLE partitioned_telemetry DETACH PARTITION ${name} CONCURRENTLY`,
);
await dbClient.query(`DROP TABLE ${name}`);
}
} catch (error) {
console.error('Error dropping old partition:', error);
process.exitCode = 1;
} finally {
// Safely close the database connection when done
await dbClient.end();
}
}
dropOldPartitions();
Note: If you need to keep the data, export the detached table before dropping it, for example with COPY ... TO STDOUT (or pg_dump -t) streamed to Amazon S3, and verify the upload before the DROP TABLE. If a DETACH ... CONCURRENTLY is interrupted, the partition is left in a pending state; finish it with ALTER TABLE ... DETACH PARTITION ... FINALIZE.
Summary
Scaling a database doesn't always mean adopting a new technology stack or migrating to a specialized time-series database. Understanding how PostgreSQL stores and cleans up data lets you go a long way with the tools you already have. If you want help applying this to an existing production database, see our backend development services.
By implementing native PostgreSQL declarative partitioning, we solved three major scaling problems:
- Insert speeds: Each partition's indexes stay small, so index maintenance on the hot partition is cheaper.
- Query speeds: Queries that filter on time only scan the relevant "drawers" thanks to partition pruning.
- Storage and cleanup: Detaching and dropping whole partitions removes old data without
DELETEbloat orVACUUMwork.
Sources
- PostgreSQL docs: Table Partitioning (declarative partitioning, index propagation, primary key rules, detach locking)
- PostgreSQL docs: ALTER TABLE (
DETACH PARTITION ... CONCURRENTLYandFINALIZE) - pg_partman on GitHub (automated partition creation and retention)
- node-postgres documentation: Pool
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why does deleting old telemetry data in PostgreSQL cause performance issues?
In PostgreSQL, deleting rows doesn't immediately free disk space because of Multi-Version Concurrency Control (MVCC). It leaves "dead tuples" behind until VACUUM marks the space reusable, and a regular VACUUM rarely returns it to the operating system. On large tables that cleanup is heavy I/O work that competes with live traffic.
What is declarative table partitioning in PostgreSQL?
Declarative table partitioning allows you to divide a massive table into smaller, more manageable "child" tables based on a specific rule, such as a date range. A "parent" table acts as a router, automatically sending incoming data into the correct child partition. This makes querying recent data and archiving old time-series data significantly faster.
Do I need to modify my Node.js application code to use partitioned tables?
Usually not. When your Node.js app inserts a row into the parent table, PostgreSQL evaluates the partition key (like the created_at timestamp) and routes the row to the correct child table. You may need to adjust queries so they filter on the partition key, and any primary key or unique constraint must include it.
How does table partitioning solve the index bottleneck for high-volume inserts?
Adding an index to a massive, unpartitioned table slows down insert speeds because the database must update a giant index for every new event. Partitioning breaks the data into smaller chunks, meaning the database only needs to update the much smaller index of the specific active child partition, keeping insert speeds fast.
Should I migrate to a specialized time-series database instead of partitioning PostgreSQL?
Migrating to a specialized time-series database means new infrastructure and a data migration. For many applications, native PostgreSQL partitioning provides enough headroom for high-volume event logging while allowing you to keep your existing, familiar database stack.
