24.1. 例行性資料清理1

24.1.1. Vacuuming Basics

24.1.2. Recovering Disk Space

24.1.3. Updating Planner Statistics

24.1.4. Updating The Visibility Map

24.1.5. Preventing Transaction ID Wraparound Failures

24.1.6. The Autovacuum Daemon

PostgreSQLdatabases require periodic maintenance known asvacuuming. For many installations, it is sufficient to let vacuuming be performed by theautovacuum daemon, which is described inSection 24.1.6. You might need to adjust the autovacuuming parameters described there to obtain best results for your situation. Some database administrators will want to supplement or replace the daemon's activities with manually-managedVACUUMcommands, which typically are executed according to a schedule bycronorTask Schedulerscripts. To set up manually-managed vacuuming properly, it is essential to understand the issues discussed in the next few subsections. Administrators who rely on autovacuuming may still wish to skim this material to help them understand and adjust autovacuuming.

24.1.1. Vacuuming Basics

PostgreSQL'sVACUUMcommand has to process each table on a regular basis for several reasons:

  1. To recover or reuse disk space occupied by updated or deleted rows.
  2. To update data statistics used by the PostgreSQL query planner.
  3. To update the visibility map, which speeds up index-only scans .
  4. To protect against loss of very old data due to transaction ID wraparound or multixact ID wraparound .

Each of these reasons dictates performingVACUUMoperations of varying frequency and scope, as explained in the following subsections.

There are two variants ofVACUUM: standardVACUUMandVACUUM FULL.VACUUM FULLcan reclaim more disk space but runs much more slowly. Also, the standard form ofVACUUMcan run in parallel with production database operations. (Commands such asSELECT,INSERT,UPDATE, andDELETEwill continue to function normally, though you will not be able to modify the definition of a table with commands such asALTER TABLEwhile it is being vacuumed.)VACUUM FULLrequires exclusive lock on the table it is working on, and therefore cannot be done in parallel with other use of the table. Generally, therefore, administrators should strive to use standardVACUUMand avoidVACUUM FULL.

VACUUMcreates a substantial amount of I/O traffic, which can cause poor performance for other active sessions. There are configuration parameters that can be adjusted to reduce the performance impact of background vacuuming — seeSection 19.4.4.

24.1.2. Recovering Disk Space

InPostgreSQL, anUPDATEorDELETEof a row does not immediately remove the old version of the row. This approach is necessary to gain the benefits of multiversion concurrency control (MVCC, seeChapter 13): the row version must not be deleted while it is still potentially visible to other transactions. But eventually, an outdated or deleted row version is no longer of interest to any transaction. The space it occupies must then be reclaimed for reuse by new rows, to avoid unbounded growth of disk space requirements. This is done by runningVACUUM.

The standard form ofVACUUMremoves dead row versions in tables and indexes and marks the space available for future reuse. However, it will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free and an exclusive table lock can be easily obtained. In contrast,VACUUM FULLactively compacts tables by writing a complete new version of the table file with no dead space. This minimizes the size of the table, but can take a long time. It also requires extra disk space for the new copy of the table, until the operation completes.

The usual goal of routine vacuuming is to do standardVACUUMs often enough to avoid needingVACUUM FULL. The autovacuum daemon attempts to work this way, and in fact will never issueVACUUM FULL. In this approach, the idea is not to keep tables at their minimum size, but to maintain steady-state usage of disk space: each table occupies space equivalent to its minimum size plus however much space gets used up between vacuumings. AlthoughVACUUM FULLcan be used to shrink a table back to its minimum size and return the disk space to the operating system, there is not much point in this if the table will just grow again in the future. Thus, moderately-frequent standardVACUUMruns are a better approach than infrequentVACUUM FULLruns for maintaining heavily-updated tables.

Some administrators prefer to schedule vacuuming themselves, for example doing all the work at night when load is low. The difficulty with doing vacuuming according to a fixed schedule is that if a table has an unexpected spike in update activity, it may get bloated to the point thatVACUUM FULLis really necessary to reclaim space. Using the autovacuum daemon alleviates this problem, since the daemon schedules vacuuming dynamically in response to update activity. It is unwise to disable the daemon completely unless you have an extremely predictable workload. One possible compromise is to set the daemon's parameters so that it will only react to unusually heavy update activity, thus keeping things from getting out of hand, while scheduledVACUUMs are expected to do the bulk of the work when the load is typical.

For those not using autovacuum, a typical approach is to schedule a database-wideVACUUMonce a day during a low-usage period, supplemented by more frequent vacuuming of heavily-updated tables as necessary. (Some installations with extremely high update rates vacuum their busiest tables as often as once every few minutes.) If you have multiple databases in a cluster, don't forget toVACUUMeach one; the programvacuumdbmight be helpful.


PlainVACUUMmay not be satisfactory when a table contains large numbers of dead row versions as a result of massive update or delete activity. If you have such a table and you need to reclaim the excess disk space it occupies, you will need to useVACUUM FULL, or alternativelyCLUSTERor one of the table-rewriting variants ofALTER TABLE. These commands rewrite an entire new copy of the table and build new indexes for it. All these options require exclusive lock. Note that they also temporarily use extra disk space approximately equal to the size of the table, since the old copies of the table and indexes can't be released until the new ones are complete.


If you have a table whose entire contents are deleted on a periodic basis, consider doing it withTRUNCATErather than usingDELETEfollowed byVACUUM.TRUNCATEremoves the entire content of the table immediately, without requiring a subsequentVACUUMorVACUUM FULLto reclaim the now-unused disk space. The disadvantage is that strict MVCC semantics are violated.

24.1.3. Updating Planner Statistics

ThePostgreSQLquery planner relies on statistical information about the contents of tables in order to generate good plans for queries. These statistics are gathered by theANALYZEcommand, which can be invoked by itself or as an optional step inVACUUM. It is important to have reasonably accurate statistics, otherwise poor choices of plans might degrade database performance.

The autovacuum daemon, if enabled, will automatically issueANALYZEcommands whenever the content of a table has changed sufficiently. However, administrators might prefer to rely on manually-scheduledANALYZEoperations, particularly if it is known that update activity on a table will not affect the statistics of“interesting”columns. The daemon schedulesANALYZEstrictly as a function of the number of rows inserted or updated; it has no knowledge of whether that will lead to meaningful statistical changes.

As with vacuuming for space recovery, frequent updates of statistics are more useful for heavily-updated tables than for seldom-updated ones. But even for a heavily-updated table, there might be no need for statistics updates if the statistical distribution of the data is not changing much. A simple rule of thumb is to think about how much the minimum and maximum values of the columns in the table change. For example, atimestampcolumn that contains the time of row update will have a constantly-increasing maximum value as rows are added and updated; such a column will probably need more frequent statistics updates than, say, a column containing URLs for pages accessed on a website. The URL column might receive changes just as often, but the statistical distribution of its values probably changes relatively slowly.

It is possible to runANALYZEon specific tables and even just specific columns of a table, so the flexibility exists to update some statistics more frequently than others if your application requires it. In practice, however, it is usually best to just analyze the entire database, because it is a fast operation.ANALYZEuses a statistically random sampling of the rows of a table rather than reading every single row.


Although per-column tweaking ofANALYZEfrequency might not be very productive, you might find it worthwhile to do per-column adjustment of the level of detail of the statistics collected byANALYZE. Columns that are heavily used inWHEREclauses and have highly irregular data distributions might require a finer-grain data histogram than other columns. SeeALTER TABLE SET STATISTICS, or change the database-wide default using thedefault_statistics_targetconfiguration parameter.

Also, by default there is limited information available about the selectivity of functions. However, if you create an expression index that uses a function call, useful statistics will be gathered about the function, which can greatly improve query plans that use the expression index.


The autovacuum daemon does not issueANALYZEcommands for foreign tables, since it has no means of determining how often that might be useful. If your queries require statistics on foreign tables for proper planning, it's a good idea to run manually-managedANALYZEcommands on those tables on a suitable schedule.

24.1.4. Updating The Visibility Map

Vacuum maintains avisibility mapfor each table to keep track of which pages contain only tuples that are known to be visible to all active transactions (and all future transactions, until the page is again modified). This has two purposes. First, vacuum itself can skip such pages on the next run, since there is nothing to clean up.

Second, it allowsPostgreSQLto answer some queries using only the index, without reference to the underlying table. SincePostgreSQLindexes don't contain tuple visibility information, a normal index scan fetches the heap tuple for each matching index entry, to check whether it should be seen by the current transaction. Anindex-only scan, on the other hand, checks the visibility map first. If it's known that all tuples on the page are visible, the heap fetch can be skipped. This is most useful on large data sets where the visibility map can prevent disk accesses. The visibility map is vastly smaller than the heap, so it can easily be cached even when the heap is very large.

24.1.5. Preventing Transaction ID Wraparound Failures

PostgreSQL'sMVCCtransaction semantics depend on being able to compare transaction ID (XID) numbers: a row version with an insertion XID greater than the current transaction's XID is“in the future”and should not be visible to the current transaction. But since transaction IDs have limited size (32 bits) a cluster that runs for a long time (more than 4 billion transactions) would suffertransaction ID wraparound: the XID counter wraps around to zero, and all of a sudden transactions that were in the past appear to be in the future — which means their output become invisible. In short, catastrophic data loss. (Actually the data is still there, but that's cold comfort if you cannot get at it.) To avoid this, it is necessary to vacuum every table in every database at least once every two billion transactions.

The reason that periodic vacuuming solves the problem is thatVACUUMwill mark rows asfrozen, indicating that they were inserted by a transaction that committed sufficiently far in the past that the effects of the inserting transaction are certain to be visible to all current and future transactions. Normal XIDs are compared using modulo-232arithmetic. This means that for every normal XID, there are two billion XIDs that are“older”and two billion that are“newer”; another way to say it is that the normal XID space is circular with no endpoint. Therefore, once a row version has been created with a particular normal XID, the row version will appear to be“in the past”for the next two billion transactions, no matter which normal XID we are talking about. If the row version still exists after more than two billion transactions, it will suddenly appear to be in the future. To prevent this,PostgreSQLreserves a special XID,FrozenTransactionId, which does not follow the normal XID comparison rules and is always considered older than every normal XID. Frozen row versions are treated as if the inserting XID wereFrozenTransactionId, so that they will appear to be“in the past”to all normal transactions regardless of wraparound issues, and so such row versions will be valid until deleted, no matter how long that is.


InPostgreSQLversions before 9.4, freezing was implemented by actually replacing a row's insertion XID withFrozenTransactionId, which was visible in the row'sxminsystem column. Newer versions just set a flag bit, preserving the row's originalxminfor possible forensic use. However, rows withxminequal toFrozenTransactionId(2) may still be found in databasespg_upgrade'd from pre-9.4 versions.

Also, system catalogs may contain rows withxminequal toBootstrapTransactionId(1), indicating that they were inserted during the first phase ofinitdb. LikeFrozenTransactionId, this special XID is treated as older than every normal XID.

vacuum_freeze_min_agecontrols how old an XID value has to be before rows bearing that XID will be frozen. Increasing this setting may avoid unnecessary work if the rows that would otherwise be frozen will soon be modified again, but decreasing this setting increases the number of transactions that can elapse before the table must be vacuumed again.

VACUUMuses thevisibility mapto determine which pages of a table must be scanned. Normally, it will skip pages that don't have any dead row versions even if those pages might still have row versions with old XID values. Therefore, normalVACUUMs won't always freeze every old row version in the table. Periodically,VACUUMwill perform anaggressive vacuum, skipping only those pages which contain neither dead rows nor any unfrozen XID or MXID values.vacuum_freeze_table_agecontrols whenVACUUMdoes that: all-visible but not all-frozen pages are scanned if the number of transactions that have passed since the last such scan is greater thanvacuum_freeze_table_ageminusvacuum_freeze_min_age. Settingvacuum_freeze_table_ageto 0 forcesVACUUMto use this more aggressive strategy for all scans.

The maximum time that a table can go unvacuumed is two billion transactions minus thevacuum_freeze_min_agevalue at the time of the last aggressive vacuum. If it were to go unvacuumed for longer than that, data loss could result. To ensure that this does not happen, autovacuum is invoked on any table that might contain unfrozen rows with XIDs older than the age specified by the configuration parameterautovacuum_freeze_max_age. (This will happen even if autovacuum is disabled.)

This implies that if a table is not otherwise vacuumed, autovacuum will be invoked on it approximately once everyautovacuum_freeze_max_ageminusvacuum_freeze_min_agetransactions. For tables that are regularly vacuumed for space reclamation purposes, this is of little importance. However, for static tables (including tables that receive inserts, but no updates or deletes), there is no need to vacuum for space reclamation, so it can be useful to try to maximize the interval between forced autovacuums on very large static tables. Obviously one can do this either by increasingautovacuum_freeze_max_ageor decreasingvacuum_freeze_min_age.

The effective maximum forvacuum_freeze_table_ageis 0.95 *autovacuum_freeze_max_age; a setting higher than that will be capped to the maximum. A value higher thanautovacuum_freeze_max_agewouldn't make sense because an anti-wraparound autovacuum would be triggered at that point anyway, and the 0.95 multiplier leaves some breathing room to run a manualVACUUMbefore that happens. As a rule of thumb,vacuum_freeze_table_ageshould be set to a value somewhat belowautovacuum_freeze_max_age, leaving enough gap so that a regularly scheduledVACUUMor an autovacuum triggered by normal delete and update activity is run in that window. Setting it too close could lead to anti-wraparound autovacuums, even though the table was recently vacuumed to reclaim space, whereas lower values lead to more frequent aggressive vacuuming.

The sole disadvantage of increasingautovacuum_freeze_max_age(andvacuum_freeze_table_agealong with it) is that thepg_xactandpg_commit_tssubdirectories of the database cluster will take more space, because it must store the commit status and (iftrack_commit_timestampis enabled) timestamp of all transactions back to theautovacuum_freeze_max_agehorizon. The commit status uses two bits per transaction, so ifautovacuum_freeze_max_ageis set to its maximum allowed value of two billion,pg_xactcan be expected to grow to about half a gigabyte andpg_commit_tsto about 20GB. If this is trivial compared to your total database size, settingautovacuum_freeze_max_ageto its maximum allowed value is recommended. Otherwise, set it depending on what you are willing to allow forpg_xactandpg_commit_tsstorage. (The default, 200 million transactions, translates to about 50MB ofpg_xactstorage and about 2GB ofpg_commit_tsstorage.)

One disadvantage of decreasingvacuum_freeze_min_ageis that it might causeVACUUMto do useless work: freezing a row version is a waste of time if the row is modified soon thereafter (causing it to acquire a new XID). So the setting should be large enough that rows are not frozen until they are unlikely to change any more.

To track the age of the oldest unfrozen XIDs in a database,VACUUMstores XID statistics in the system tablespg_classandpg_database. In particular, therelfrozenxidcolumn of a table'spg_classrow contains the freeze cutoff XID that was used by the last aggressiveVACUUMfor that table. All rows inserted by transactions with XIDs older than this cutoff XID are guaranteed to have been frozen. Similarly, thedatfrozenxidcolumn of a database'spg_databaserow is a lower bound on the unfrozen XIDs appearing in that database — it is just the minimum of the per-tablerelfrozenxidvalues within the database. A convenient way to examine this information is to execute queries such as:

SELECT c.oid::regclass as table_name,
       greatest(age(c.relfrozenxid),age(t.relfrozenxid)) as age
FROM pg_class c
LEFT JOIN pg_class t ON c.reltoastrelid = t.oid
WHERE c.relkind IN ('r', 'm');

SELECT datname, age(datfrozenxid) FROM pg_database;

Theagecolumn measures the number of transactions from the cutoff XID to the current transaction's XID.

VACUUMnormally only scans pages that have been modified since the last vacuum, butrelfrozenxidcan only be advanced when every page of the table that might contain unfrozen XIDs is scanned. This happens whenrelfrozenxidis more thanvacuum_freeze_table_agetransactions old, whenVACUUM'sFREEZEoption is used, or when all pages that are not already all-frozen happen to require vacuuming to remove dead row versions. WhenVACUUMscans every page in the table that is not already all-frozen, it should setage(relfrozenxid)to a value just a little more than thevacuum_freeze_min_agesetting that was used (more by the number of transactions started since theVACUUMstarted). If norelfrozenxid-advancingVACUUMis issued on the table untilautovacuum_freeze_max_ageis reached, an autovacuum will soon be forced for the table.

If for some reason autovacuum fails to clear old XIDs from a table, the system will begin to emit warning messages like this when the database's oldest XIDs reach ten million transactions from the wraparound point:

WARNING:  database "mydb" must be vacuumed within 177009986 transactions
HINT:  To avoid a database shutdown, execute a database-wide VACUUM in "mydb".

(A manualVACUUMshould fix the problem, as suggested by the hint; but note that theVACUUMmust be performed by a superuser, else it will fail to process system catalogs and thus not be able to advance the database'sdatfrozenxid.) If these warnings are ignored, the system will shut down and refuse to start any new transactions once there are fewer than 1 million transactions left until wraparound:

ERROR:  database is not accepting commands to avoid wraparound data loss in database "mydb"
HINT:  Stop the postmaster and vacuum that database in single-user mode.

The 1-million-transaction safety margin exists to let the administrator recover without data loss, by manually executing the requiredVACUUMcommands. However, since the system will not execute commands once it has gone into the safety shutdown mode, the only way to do this is to stop the server and start the server in single-user mode to executeVACUUM. The shutdown mode is not enforced in single-user mode. See thepostgresreference page for details about using single-user mode. Multixacts and Wraparound

_Multixact IDs_are used to support row locking by multiple transactions. Since there is only limited space in a tuple header to store lock information, that information is encoded as a“multiple transaction ID”, or multixact ID for short, whenever there is more than one transaction concurrently locking a row. Information about which transaction IDs are included in any particular multixact ID is stored separately in thepg_multixactsubdirectory, and only the multixact ID appears in thexmaxfield in the tuple header. Like transaction IDs, multixact IDs are implemented as a 32-bit counter and corresponding storage, all of which requires careful aging management, storage cleanup, and wraparound handling. There is a separate storage area which holds the list of members in each multixact, which also uses a 32-bit counter and which must also be managed.

WheneverVACUUMscans any part of a table, it will replace any multixact ID it encounters which is older thanvacuum_multixact_freeze_min_ageby a different value, which can be the zero value, a single transaction ID, or a newer multixact ID. For each table,pg_class.relminmxidstores the oldest possible multixact ID still appearing in any tuple of that table. If this value is older thanvacuum_multixact_freeze_table_age, an aggressive vacuum is forced. As discussed in the previous section, an aggressive vacuum means that only those pages which are known to be all-frozen will be skipped.mxid_age()can be used onpg_class.relminmxidto find its age.

AggressiveVACUUMscans, regardless of what causes them, enable advancing the value for that table. Eventually, as all tables in all databases are scanned and their oldest multixact values are advanced, on-disk storage for older multixacts can be removed.

As a safety device, an aggressive vacuum scan will occur for any table whose multixact-age is greater thanautovacuum_multixact_freeze_max_age. Aggressive vacuum scans will also occur progressively for all tables, starting with those that have the oldest multixact-age, if the amount of used member storage space exceeds the amount 50% of the addressable storage space. Both of these kinds of aggressive scans will occur even if autovacuum is nominally disabled.

24.1.6. The Autovacuum Daemon

PostgreSQLhas an optional but highly recommended feature calledautovacuum, whose purpose is to automate the execution ofVACUUMandANALYZEcommands. When enabled, autovacuum checks for tables that have had a large number of inserted, updated or deleted tuples. These checks use the statistics collection facility; therefore, autovacuum cannot be used unlesstrack_countsis set totrue. In the default configuration, autovacuuming is enabled and the related configuration parameters are appropriately set.

The“autovacuum daemon”actually consists of multiple processes. There is a persistent daemon process, called theautovacuum launcher, which is in charge of startingautovacuum worker_processes for all databases. The launcher will distribute the work across time, attempting to start one worker within each database everyautovacuum_naptimeseconds. (Therefore, if the installation hasNdatabases, a new worker will be launched everyautovacuum_naptime/N_seconds.) A maximum ofautovacuum_max_workersworker processes are allowed to run at the same time. If there are more thanautovacuum_max_workersdatabases to be processed, the next database will be processed as soon as the first worker finishes. Each worker process will check each table within its database and executeVACUUMand/orANALYZEas needed.log_autovacuum_min_durationcan be set to monitor autovacuum workers' activity.

If several large tables all become eligible for vacuuming in a short amount of time, all autovacuum workers might become occupied with vacuuming those tables for a long period. This would result in other tables and databases not being vacuumed until a worker becomes available. There is no limit on how many workers might be in a single database, but workers do try to avoid repeating work that has already been done by other workers. Note that the number of running workers does not count towardsmax_connectionsorsuperuser_reserved_connectionslimits.

Tables whoserelfrozenxidvalue is more thanautovacuum_freeze_max_agetransactions old are always vacuumed (this also applies to those tables whose freeze max age has been modified via storage parameters; see below). Otherwise, if the number of tuples obsoleted since the lastVACUUMexceeds the“vacuum threshold”, the table is vacuumed. The vacuum threshold is defined as:

vacuum threshold = vacuum base threshold + vacuum scale factor * number of tuples

where the vacuum base threshold isautovacuum_vacuum_threshold, the vacuum scale factor isautovacuum_vacuum_scale_factor, and the number of tuples ispg_class.reltuples. The number of obsolete tuples is obtained from the statistics collector; it is a semi-accurate count updated by eachUPDATEandDELETEoperation. (It is only semi-accurate because some information might be lost under heavy load.) If therelfrozenxidvalue of the table is more thanvacuum_freeze_table_agetransactions old, an aggressive vacuum is performed to freeze old tuples and advancerelfrozenxid; otherwise, only pages that have been modified since the last vacuum are scanned.

For analyze, a similar condition is used: the threshold, defined as:

analyze threshold = analyze base threshold + analyze scale factor * number of tuples

is compared to the total number of tuples inserted, updated, or deleted since the lastANALYZE.

Temporary tables cannot be accessed by autovacuum. Therefore, appropriate vacuum and analyze operations should be performed via session SQL commands.

The default thresholds and scale factors are taken frompostgresql.conf, but it is possible to override them (and many other autovacuum control parameters) on a per-table basis; seeStorage Parametersfor more information. If a setting has been changed via a table's storage parameters, that value is used when processing that table; otherwise the global settings are used. SeeSection 19.10for more details on the global settings.

When multiple workers are running, the autovacuum cost delay parameters (seeSection 19.4.4) are“balanced”among all the running workers, so that the total I/O impact on the system is the same regardless of the number of workers actually running. However, any workers processing tables whose per-tableautovacuum_vacuum_cost_delayorautovacuum_vacuum_cost_limitstorage parameters have been set are not considered in the balancing algorithm.

1. PostgreSQL: Documentation: 10: 24.1. Routine Vacuuming

results matching ""

    No results matching ""