Picture the call. Someone at a Sharjah trading company says the ERP "has become slow, especially the stock report", and you are the person who inherited the server. Nobody wrote down what database sits underneath. You open a connection and discover it is PostgreSQL, 40 GB on disk, last touched by a consultant who left two years ago. Where do you even start?
This is a practical guide to PostgreSQL maintenance for exactly that person: the IT officer, the developer at a software house, or the accountant's nephew who "knows computers". It covers what to do daily, weekly and monthly, what autovacuum does for you, where it falls short, how to spot table bloat, what to rebuild and what each command locks. We have kept the SQL real, so you can paste it into psql or any SQL client and see your own numbers.
One honest note first. PostgreSQL is very good at looking after itself, and a lot of databases run for years on defaults without drama. The trouble is the ones that do not, because they are the ones holding your invoices.
What PostgreSQL maintenance actually means
PostgreSQL uses multiversion concurrency control (MVCC). When a row is updated or deleted, the old version is not erased on the spot. It stays in the table as a dead tuple until a VACUUM marks that space as reusable. This is what lets one user run a long report while another posts invoices without either blocking the other. It is a good design, and it has one side effect: somebody has to clean up.
That cleaning is most of PostgreSQL maintenance. In practice it comes down to four jobs.
- Reclaim dead rows with VACUUM, so tables stop growing for no reason.
- Refresh statistics with ANALYZE, so the query planner picks sensible plans.
- Keep indexes healthy by rebuilding bloated ones and removing ones nobody uses.
- Watch the vital signs: slow queries, cache hit ratio, connections, database size growth and deadlocks.
Backups sit next to this list rather than inside it. They matter enough to have their own guide, PostgreSQL backup and restore on Windows, and we will only touch them briefly here.
What autovacuum does, and where it falls short
Autovacuum is a background process that runs VACUUM and ANALYZE for you, table by table, when enough rows have changed. It is switched on by default, and you should leave it on. Switching it off to "save resources" is one of the most expensive mistakes we see.
How it decides when to run
By default, autovacuum vacuums a table once the number of dead rows passes a threshold of 50 plus 20 per cent of the table's rows (autovacuum_vacuum_threshold and autovacuum_vacuum_scale_factor). It analyses once changes pass 50 plus 10 per cent. For a table with 100,000 rows, that is fine. For a table with 50 million rows, 20 per cent means ten million dead rows before anything happens. That is the first place the defaults fall short.
Where it struggles
Big, busy tables are the classic case. A sales or stock-movement table that takes constant inserts and updates can outrun the default settings. You can give such a table its own thresholds:
ALTER TABLE invoice_lines SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_analyze_scale_factor = 0.01
);
The table name is only an example. The point is that per-table settings are cheap, safe and reversible, and they often fix a "slow since last quarter" complaint without touching anything else.
The second weak spot is anything that holds back the oldest transaction. VACUUM cannot remove a dead row that some open transaction might still need to see. A session left "idle in transaction", a forgotten long report, an abandoned replication slot or a stuck prepared transaction can all keep dead rows alive for days, however often autovacuum runs. If vacuum seems to run and bloat does not shrink, look here first.
Third, autovacuum is deliberately polite. It throttles itself with cost-based delays so it does not hurt your users, which means a very large table can take a long time to get through. And fourth, it also protects you from transaction ID wraparound, a rare but serious condition. A quick check costs nothing:
SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;
If those numbers keep climbing towards the hundreds of millions without ever dropping, autovacuum is not completing its freezing work and someone needs to investigate. Tracking it weekly is enough.
How to spot table bloat and dead tuples
Bloat is what you get when dead rows pile up faster than they are reclaimed. The table and its indexes take more disk than the live data needs, scans read more pages, caches fill with junk, and backups get bigger. Remember that a plain VACUUM makes space reusable inside the file but usually does not shrink the file itself, so a bloated table can stay big even after a good clean-up. Reuse is the win, not a smaller number in Explorer.
Start with the statistics PostgreSQL already keeps:
SELECT relname,
n_live_tup,
n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_autovacuum,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 15;
Read this the way a mechanic reads a gauge. A few thousand dead rows on a big table is normal. A dead percentage above roughly 20 per cent with a last_autovacuum from weeks ago deserves attention. A NULL in last_autovacuum on a busy table means autovacuum has never completed on it since the statistics were last reset.
These numbers are estimates. If you need hard figures, the pgstattuple extension (CREATE EXTENSION pgstattuple;) can measure dead space and free space exactly, though it reads the whole table, so do not point it at your biggest table at 10 a.m. on a Sunday. Then compare table sizes over time:
SELECT relname,
pg_size_pretty(pg_total_relation_size(relid)) AS total,
pg_size_pretty(pg_relation_size(relid)) AS table_only,
pg_size_pretty(pg_indexes_size(relid)) AS indexes
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;
Write the top five sizes in a notebook once a month. A table that doubles in size while its row count barely moves is telling you something.
PostgreSQL maintenance tasks at a glance
This table is the cheat sheet we wish we had been handed. Keep the locking column in mind when you choose a time of day.
| Task | What it does | How often | Locking / impact |
|---|---|---|---|
| Autovacuum | Removes dead rows and refreshes statistics in the background | Always on | Light; does not block normal reads and writes |
| VACUUM (ANALYZE) | Makes dead-row space reusable and updates planner statistics | Weekly on busy tables, or after big imports | Does not block reads or writes; blocks schema changes on that table |
| ANALYZE | Updates statistics only | After large loads or deletes | Light |
| REINDEX ... CONCURRENTLY | Builds a fresh copy of an index, then swaps it in (PostgreSQL 12+) | When an index is clearly bloated | Does not block writes, but takes longer and uses extra disk |
| REINDEX (plain) | Rebuilds an index in place | Rarely; quiet windows only | Blocks writes to the table for the duration |
| VACUUM FULL | Rewrites the whole table into a new file and returns space to the operating system | Monthly or less, badly bloated tables only | Exclusive lock: no reads or writes on that table |
| Unused index review | Finds indexes with zero scans so you can drop them | Monthly | Read-only to check; DROP INDEX takes a brief lock |
| Slow query review | Reads pg_stat_statements or the slow-query log | Weekly | None |
| Size and connection check | Compares database and table size and connection count with last week | Daily or weekly | None |
| Backup and restore test | Proves you can recover | Backup daily; restore test monthly | pg_dump does not block normal work, but adds load |
VACUUM, VACUUM FULL and REINDEX: what to run, and what it locks
Plain VACUUM is your friend
A normal VACUUM is safe to run while people work. It takes a lock that allows reads and writes, and only conflicts with things like ALTER TABLE or another VACUUM on the same table. Combined with ANALYZE it also refreshes statistics in one pass:
VACUUM (ANALYZE, VERBOSE) invoice_lines;
VERBOSE prints how many dead row versions were found and removed, and how many could not be removed yet. That last number is a useful clue. If it stays high, you are back to the long-transaction suspects above.
VACUUM FULL is a different animal
VACUUM FULL rewrites the entire table into a new file. That does return space to the operating system, but it holds an exclusive lock on the table for the whole time, and it needs enough free disk for a second copy. On a table with millions of rows, that can mean minutes or hours when nobody can read or write it. Honestly, most databases need it rarely or never. Use it for tables that are badly bloated and not likely to grow back, at a time when the business is not posting to them.
If you cannot afford the lock, there are extensions such as pg_repack that rebuild tables with much shorter locks, but they need to be installed on the server, and on a locked-down production box that is a conversation to have in advance.
REINDEX, and the CONCURRENTLY option
Indexes bloat as well, and rebuilding them gives you a compact copy. A plain REINDEX blocks writes to the table while it runs. From PostgreSQL 12 you can avoid that:
REINDEX TABLE CONCURRENTLY invoice_lines;
REINDEX INDEX CONCURRENTLY idx_invoice_lines_item; -- one index at a time
The concurrent form builds the new index alongside the old one and swaps them, so normal traffic keeps flowing. It takes longer, needs extra disk, and cannot run inside a transaction block. If it is cancelled part way, it can leave an invalid index behind, with a name ending in _ccnew, that you need to drop by hand. Check for those after any failure. On PostgreSQL 11 or older you do not have this option, which is one more reason to plan an upgrade.
Unused and missing indexes
Every index speeds up some reads and slows down every write. After a few years of "let's add an index for that report", plenty of systems carry indexes that no query touches. You can list candidates like this:
SELECT s.relname AS table_name,
s.indexrelname AS index_name,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
AND NOT i.indisunique
ORDER BY pg_relation_size(s.indexrelid) DESC
LIMIT 20;
Treat the result as a shortlist, not a hit list. The counters only cover the period since the statistics were last reset, so an index that serves the quarter-end VAT report may show zero scans in mid-month. Indexes that enforce unique or primary key constraints are excluded above for good reason. Before dropping anything, ask the application owner, check how long the statistics have been collecting, and keep the CREATE INDEX statement so you can put it back.
The opposite problem is just as real. A foreign key column without an index can make joins and deletes on the parent table crawl. If a particular screen is slow and the plan shows a sequential scan on a big child table, a missing index is the likely cause.
What to monitor: slow queries, cache hit ratio, connections, size and deadlocks
Slow queries
The most useful single tool here is the pg_stat_statements extension. It needs to be listed in shared_preload_libraries (a restart), then created with CREATE EXTENSION pg_stat_statements. After that:
SELECT calls,
round(total_exec_time::numeric, 0) AS total_ms,
round(mean_exec_time::numeric, 1) AS mean_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Those column names are for PostgreSQL 13 and newer; older versions call them total_time and mean_time. Sorting by total time matters: a 50 ms query that runs a million times a day costs more than a 20-second report run once. If you cannot install the extension, set log_min_duration_statement to something like 1000 (milliseconds) and read the log.
Cache hit ratio
This tells you how often PostgreSQL found the data it needed in memory instead of asking the disk.
SELECT datname,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS cache_hit_pct,
deadlocks,
pg_size_pretty(pg_database_size(datname)) AS size
FROM pg_stat_database
WHERE datname = current_database();
For a transactional system such as an ERP, you generally expect a high figure, in the high 90s. But the trend matters more than the absolute number. A ratio that drops suddenly after a data import or a new report usually means something started reading far more than before. Note that this counts PostgreSQL's own buffer cache, and the operating system may still be serving some of the "reads" from its cache.
Connections, size growth and deadlocks
SELECT count(*) AS connections,
current_setting('max_connections') AS max_connections
FROM pg_stat_activity;
If connections regularly sit near the maximum, the usual cause is an application that opens a connection per request and never lets go, not too small a limit. Size growth is the third vital sign: record pg_database_size() weekly, so a slow climb or a sudden jump shows up before the disk fills. Deadlocks live in the same pg_stat_database view. A handful is not an emergency, since PostgreSQL detects them and cancels one session, but a counter that rises every week means two parts of the application lock rows in opposite orders. That is a bug to hand to the developers, with the log entries as evidence. Setting log_lock_waits = on helps you catch these.
A weekly PostgreSQL maintenance routine you can actually keep
Routines fail when they are too ambitious. This is deliberately small. A sensible split looks like this:
- Daily (two minutes): confirm last night's backup exists and has a sensible size; glance at disk space and connection count.
- Weekly (20 to 30 minutes): the eight steps below.
- Monthly (an hour, at a quiet time): review unused indexes, look at VACUUM FULL candidates, compare table sizes with last month and restore a backup into a scratch database.
Here is the weekly routine in order.
- Check the health numbers. Look at connections against max_connections, database size against last week, the cache hit ratio and the deadlock counter. You are looking for change, not perfection.
- Look for long-running and idle-in-transaction sessions. Query pg_stat_activity for old transactions. One forgotten session can stop VACUUM from removing dead rows for days.
- Review dead tuples and autovacuum dates. Sort pg_stat_user_tables by n_dead_tup and check last_autovacuum and last_autoanalyze on your biggest tables. Anything with a high dead percentage and an old date needs a closer look.
- Run VACUUM (ANALYZE) on the tables that need it. Run a normal VACUUM (ANALYZE, VERBOSE) on the worst tables. It does not block normal reads and writes, so it is safe in working hours for most systems.
- Check the slowest queries. Read the top of pg_stat_statements or your slow-query log. Note anything new since last week, and anything whose average time has crept up.
- Review index usage. List indexes with zero scans and look for large tables that are read by sequential scan again and again. Note candidates only; drop or add nothing in a hurry.
- Rebuild bloated indexes concurrently. If an index is clearly bloated and you are on PostgreSQL 12 or newer, run REINDEX INDEX CONCURRENTLY at a quiet time. Save VACUUM FULL for the monthly slot.
- Confirm last night's backup and write it down. Check that the latest backup file exists, is a sensible size and was copied off the server. Keep a one-line log of what you checked and what you changed.
If you do nothing else, do steps two and three. Most of the "PostgreSQL got slow" stories we hear come down to a long transaction or a table autovacuum never caught up with.
Benefits of a steady routine
Fewer slow-system complaints
Fresh statistics and reclaimed dead rows keep the planner choosing sensible plans, so the stock report that took seconds last year does not quietly turn into minutes.
Predictable disk use
When you know how fast each table grows, you can plan storage instead of discovering the problem when the data drive hits 100 per cent. Smaller, tidier tables also back up and restore faster.
Problems found before users find them
A weekly look at connections, deadlocks and slow queries turns "the system is down" calls into a line in your notes that says "watch this".
A paper trail
When the software vendor, the accountant or the auditor asks what you do to protect the database, a dated log answers the question in one go.
Who inherits these databases: use cases by business type
Software houses with customers on PostgreSQL
If you ship an application with a PostgreSQL database on each customer's Windows server, you probably maintain dozens of databases that nobody else looks at. The weekly routine above, run once per site, is the difference between a quiet support inbox and Sunday morning phone calls.
Trading and distribution companies
Stock movements, delivery notes and invoice lines are the biggest and busiest tables, and they bloat first. This is true of any inventory and sales system, and of a CRM that reads live stock, because every quotation, order and delivery writes rows. Month-end is when the heavy reports run, so schedule your heavier jobs after it, not during it.
Services and contracting firms
Smaller databases, but long-lived ones. The risk here is neglect: an old server, no monitoring and a backup that has not been tested since installation. The monthly restore test is the most valuable habit.
Multi-branch retail and F&B groups
More connections, more simultaneous writers and more chances of lock contention. Connection counts and deadlock counters deserve a weekly look.
Day-to-day scenarios
A few scenes, all illustrative, that show how the checklist earns its keep.
- The report that got slower every month. Dead percentage on the main lines table is high and last_autovacuum is old. A per-table autovacuum setting plus one manual VACUUM (ANALYZE) fixes it.
- The disk that filled overnight. A bulk import and a wave of updates produced a lot of dead rows, and a stuck session stopped them being reclaimed. Finding the session first, then vacuuming, is the order that works.
- The migration that made everything slow. After loading historical data, nobody ran ANALYZE, so the planner was working from stale numbers. One ANALYZE and the queries behave again.
- The index nobody remembers. A 6 GB index with zero scans slowing every insert. After checking with the application owner, it goes.
Manual scripts, a general admin GUI or a dedicated tool?
You have three realistic options on Windows, and none of them is wrong. A folder of SQL and batch files run by Task Scheduler costs nothing but your time and is fully under your control. A general-purpose admin GUI usually has a maintenance dialog for VACUUM, ANALYZE and REINDEX and a server dashboard, which is good for one-off work. A dedicated tool such as PGGuard wraps the routine in a screen and ready-made plans.
| Task | Manual scripts + Task Scheduler | Admin GUI only | PGGuard |
|---|---|---|---|
| Cost | Free, but costs your time | Free | Paid, priced by number of PCs |
| Health overview | Only what your queries show | Dashboard with activity graphs | Live: connections, size and growth, active queries, deadlocks, uptime |
| Slow queries and cache hit ratio | Your own SQL | Manual queries | Slowest and most frequent queries, TPS and cache hit ratio |
| Finding bloat and dead rows | Bloat queries you maintain | Manual queries | Bloat screen, one-click VACUUM |
| VACUUM, ANALYZE, REINDEX | Anything you can script | Per object, by hand | Immediate, Weekly and Monthly plans |
| Unattended scheduling | Task Scheduler runs it overnight | No built-in scheduler (pgAgent is separate) | Plans start when you press Run |
| Works across many servers | One script set per server | Register servers, check each by hand | Add as many servers as you like |
| Skill needed | Good SQL and scripting | Know which command to run | Plans decide from what they find |
| Risk of a wrong command | You own every mistake | You own every mistake | Explorer asks before anything that changes data |
Notice the scheduling row. If you need fully unattended overnight jobs, scripts and Task Scheduler win today, and we would not pretend otherwise.
When to use PGGuard
PGGuard is our separate Windows app for PostgreSQL maintenance and backups. It will not suit everyone, and a competent DBA with good scripts does not need it. It earns its place when:

- nobody on the team writes SQL comfortably, and the weekly routine keeps slipping;
- you look after several PostgreSQL servers and want one console for all of them;
- you want bloat, dead rows and unused indexes in a list rather than a query you have to remember;
- you want backups with retention and a Google Drive copy without building the plumbing yourself.
The plans map neatly onto the routine above. The Immediate plan adds missing foreign-key indexes, makes autovacuum run more often on busy tables and refreshes stale statistics. The Weekly plan runs VACUUM ANALYZE on tables with many dead rows, rebuilds the worst indexes without locking and produces a bloat report you can keep. The Monthly plan runs VACUUM FULL on badly bloated tables, so run that one at a quiet time, plus a full ANALYZE. Each plan reads your database first, so it is not tied to a particular schema.
It runs on Windows 10 or 11 (64-bit), works with PostgreSQL 9.2 and newer, and includes pg_dump, pg_restore and psql. Read the details on the PGGuard page, or talk to the Nashora team if you want to check it fits your setup.
PostgreSQL maintenance for UAE businesses
We work with companies across Dubai, Sharjah, Abu Dhabi, Ajman, Ras Al Khaimah, Fujairah, Umm Al Quwain and Al Ain, and the pattern is familiar: a small IT team, a database that came with a business application, and a mix of mainland and free zone companies sharing a server or a cloud host. The database holds VAT invoices and TRN details (the kind of records an accounting and VAT system keeps) as well as payroll and WPS records from HR and payroll software, so a bad Sunday is expensive. The VAT 201 return and month-end close have fixed dates, which makes it worth scheduling heavy maintenance away from them.
If you would rather not set up a database server yourself, Nashora ERP installs its own on your server, for accounting, VAT, sales, inventory, CRM, HR and payroll, with plans listed on the pricing page and a free demo you can request here. If you do run your own PostgreSQL, the routine above is how you keep it healthy.
What to do next
- Run the dead-tuple query today on your busiest database and write down the top five tables, their sizes and their last_autovacuum dates.
- Check for old transactions in pg_stat_activity and for xid_age growth in pg_database.
- Put the weekly routine in your calendar as a recurring 30-minute slot, with a one-line log.
- Prove your backups restore. Our guide to PostgreSQL backup and restore on Windows walks through it step by step.
- Decide whether to automate. If scripts are not realistic for your team, see PGGuard or ask us a question through the contact page. General product questions are answered on the Nashora FAQ, and you can read more about us.
