pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: David Gould <daveg@sonic.net>
To: Alvaro Herrera <alvherre@2ndquadrant.com>
Cc: Jeff Janes <jeff.janes@gmail.com>
Cc: Tom Lane <tgl@sss.pgh.pa.us>
Cc: Pg Bugs <pgsql-bugs@postgresql.org>
Cc: Josh Berkus <josh@agliodbs.com>
Subject: Re: BUG #13750: Autovacuum slows down with large numbers of tables. More workers makes it slower.
Date: Wed, 2 Mar 2016 03:45:37 -0800
Message-ID: <20160302034537.0b1c2da7@engels> (raw)
In-Reply-To: <20160229213350.GA332809@alvherre.pgsql>
References: <20151106164649.3ed185fa@engels>
	<20160229213350.GA332809@alvherre.pgsql>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-bugs>

On Mon, 29 Feb 2016 18:33:50 -0300
Alvaro Herrera <alvherre@2ndquadrant.com> wrote:

> Hi David, did you ever post an updated version of this patch?

No. Let me fix that now. I've attached my current revision of the patch
based on master. This version is significantly better than the original
version and resolves multiple issues:

 - autovacuum workers no longer race each other
 - autovacuum workers do not revacuum each others tables
 - autovacuums workers no longer thrash the stats collector which saves a
   lot of IO when the stats is large.

Hopefully the earlier discussion and the comments in the patch are
sufficient, but please ask questions if it is not clear.

The result is that on a freshly created 40,000 table database with tiny
tables that all need an initial analyze the unpatched postgres saturates
an SSD updating the stats and manages to process less than tables per
minute. With the attached patch it processes several thousand tables per
minute.

The following is a summary of strace output for the autovacuum workers
and the stats collector while the 40k table test is running. The counts and
times are the cost per table.

postgresql 9.5:   85 tables per minute.

     Operations per Table
 calls    msec    system call        [ 4 autovacuum workers ]
------  ------    -------------------
 19.46  196.09    select(0,          <<< Waiting for stats snapshot
  3.26 1040.46    semop(43188238,    <<< Waiting for AutovacuumScheduleLock
  2.05    0.83    sendto(8,          <<< Asking for stats snapshot

 calls    msec    system call        [ stats collector ]
------  ------    -------------------
  3.02    0.05    recvfrom(8,        <<< Request for snapshot refresh
  1.55  248.64    rename("pg_stat_tmp/db_16385.tmp",  <<< Snapshot refresh


+ autovacuum contention patch: 5225 tables per minute

     Operations per Table
 calls    msec    system call        [ 4 autovacuum workers ]
------  ------    -------------------
  0.63    6.34    select(0,          <<< Waiting for stats snapshot
  0.21    0.01    sendto(8,          <<< Asking for stats snapshot
  0.07    0.00    semop(43712518,    <<< Waiting for AutovacuumLock

 calls    msec    system call        [ stats collector ]
------  ------    -------------------
  0.40    0.01    recvfrom(8,        <<< Request for snapshot refresh
  0.04    6.75    rename("pg_stat_tmp/db_16385.tmp",  <<< Snapshot refresh


Regards,

-dg


-- 
David Gould                                   daveg@sonic.net
If simplicity worked, the world would be overrun with insects.

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

autovacuum_contention_0301.patch (text/x-patch, 10.1K) download diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c index e2859df..099e57a 100644 --- a/src/backend/postmaster/autovacuum.c +++ b/src/backend/postmaster/autovacuum.c @@ -1063,6 +1063,21 @@ db_comparator(const void *a, const void *b) return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1; } + +/* qsort comparison function for oids */ +static int +oid_cmp(const void *p1, const void *p2) +{ + Oid v1 = *((const Oid *) p1); + Oid v2 = *((const Oid *) p2); + + if (v1 < v2) + return -1; + if (v1 > v2) + return 1; + return 0; +} + /* * do_start_worker * @@ -1884,16 +1899,18 @@ do_autovacuum(void) HeapTuple tuple; HeapScanDesc relScan; Form_pg_database dbForm; - List *table_oids = NIL; HASHCTL ctl; HTAB *table_toast_map; - ListCell *volatile cell; PgStat_StatDBEntry *shared; PgStat_StatDBEntry *dbentry; BufferAccessStrategy bstrategy; ScanKeyData key; TupleDesc pg_class_desc; int effective_multixact_freeze_max_age; + Oid *table_oids; + int maxoids, + numoids, + oid_idx; /* * StartTransactionCommand and CommitTransactionCommand will automatically @@ -1978,6 +1995,11 @@ do_autovacuum(void) &ctl, HASH_ELEM | HASH_BLOBS); + /* create an array of all the tables that might need action */ + maxoids = 1024; + table_oids = (Oid *) palloc(maxoids * sizeof(Oid)); + numoids = 0; + /* * Scan pg_class to determine which tables to vacuum. * @@ -2071,7 +2093,15 @@ do_autovacuum(void) { /* relations that need work are added to table_oids */ if (dovacuum || doanalyze) - table_oids = lappend_oid(table_oids, relid); + { + if (numoids >= maxoids) + { + maxoids *= 2; + table_oids = (Oid *) repalloc(table_oids, + maxoids * sizeof(Oid)); + } + table_oids[numoids++] = relid; + } /* * Remember the association for the second pass. Note: we must do @@ -2155,7 +2185,16 @@ do_autovacuum(void) /* ignore analyze for toast tables */ if (dovacuum) - table_oids = lappend_oid(table_oids, relid); + { + if (numoids >= maxoids) + { + maxoids *= 2; + table_oids = (Oid *) repalloc(table_oids, + maxoids * sizeof(Oid)); + } + table_oids[numoids++] = relid; + } + } heap_endscan(relScan); @@ -2180,12 +2219,30 @@ do_autovacuum(void) /* * Perform operations on collected tables. + * + * 1. Sort the collected oids so that workers process oids in + * the same order. + * 2. While there are items not yet visited do: + * 3. Find the last (highest) item worked on by any worker. + * 4. Claim the next item after the last one worked on. + * + * The ordering prevents workers from racing or competing with other + * workers for an item to work on. Without it there is no way to + * prevent them from trying to vacuum the same table repeatedly. */ - foreach(cell, table_oids) + + /* 1.Sort the oids to establish a consistent order for work items. */ + if (numoids > 1) + qsort(table_oids, numoids, sizeof(Oid), oid_cmp); + + /* + * 2. While there are items that have not been visited... + */ + for(oid_idx = 0; oid_idx < numoids; ) { - Oid relid = lfirst_oid(cell); autovac_table *tab; - bool skipit; + Oid relid; + Oid highest_oid_claimed; int stdVacuumCostDelay; int stdVacuumCostLimit; dlist_iter iter; @@ -2209,69 +2266,52 @@ do_autovacuum(void) } /* - * hold schedule lock from here until we're sure that this table still - * needs vacuuming. We also need the AutovacuumLock to walk the - * worker array, but we'll let go of that one quickly. + * We hold the Autovacuum lock to walk the worker array and to update + * our WorkerInfo with the chosen candidate table. */ - LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); - LWLockAcquire(AutovacuumLock, LW_SHARED); + LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); /* - * Check whether the table is being vacuumed concurrently by another - * worker. + * 3. Find the last (highest) oid claimed by any worker. */ - skipit = false; + highest_oid_claimed = InvalidOid; dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers) { WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur); - /* ignore myself */ - if (worker == MyWorkerInfo) - continue; - - /* ignore workers in other databases */ - if (worker->wi_dboid != MyDatabaseId) - continue; - - if (worker->wi_tableoid == relid) - { - skipit = true; - break; - } + if (worker->wi_dboid == MyDatabaseId + && worker->wi_tableoid >= highest_oid_claimed) + highest_oid_claimed = worker->wi_tableoid; } + + /* + * 4a. Skip past the highest_oid_claimed to find the next oid to work on. + */ + relid = InvalidOid; + while (relid <= highest_oid_claimed && oid_idx < numoids) + relid = table_oids[oid_idx++]; + if (relid <= highest_oid_claimed) + relid = InvalidOid; + /* 4b. Claim the chosen table by storing its oid in shared memory. */ + MyWorkerInfo->wi_tableoid = relid; + LWLockRelease(AutovacuumLock); - if (skipit) - { - LWLockRelease(AutovacuumScheduleLock); - continue; - } + + /* If we reached the end of the list there is nothing to do. */ + if (relid == InvalidOid) + continue; /* - * Check whether pgstat data still says we need to vacuum this table. - * It could have changed if something else processed the table while - * we weren't looking. - * - * Note: we have a special case in pgstat code to ensure that the - * stats we read are as up-to-date as possible, to avoid the problem - * that somebody just finished vacuuming this table. The window to - * the race condition is not closed but it is very small. + * Re-check whether we still need to vacuum this table. We are working + * from a list of tables that could be quite stale by now. Possibly this + * table was dropped or manually vacuumed while we weren't looking. */ MemoryContextSwitchTo(AutovacMemCxt); tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc, effective_multixact_freeze_max_age); if (tab == NULL) - { /* someone else vacuumed the table, or it went away */ - LWLockRelease(AutovacuumScheduleLock); continue; - } - - /* - * Ok, good to go. Store the table in shared memory before releasing - * the lock so that other workers don't vacuum it concurrently. - */ - MyWorkerInfo->wi_tableoid = relid; - LWLockRelease(AutovacuumScheduleLock); /* * Remember the prevailing values of the vacuum cost GUCs. We have to @@ -2479,9 +2519,7 @@ table_recheck_autovac(Oid relid, HTAB *table_toast_map, bool wraparound; AutoVacOpts *avopts; - /* use fresh stats */ - autovac_refresh_stats(); - + /* Fetch pgstats for re-checking. */ shared = pgstat_fetch_stat_dbentry(InvalidOid); dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId); @@ -2961,26 +2999,18 @@ AutoVacuumShmemInit(void) * such refreshing in the autovacuum launcher. This is mostly to avoid * rereading the pgstats files too many times in quick succession when there * are many databases. - * - * Note: we avoid throttling in the autovac worker, as it would be - * counterproductive in the recheck logic. */ static void autovac_refresh_stats(void) { - if (IsAutoVacuumLauncherProcess()) - { - static TimestampTz last_read = 0; - TimestampTz current_time; + static TimestampTz last_read = 0; + TimestampTz current_time; - current_time = GetCurrentTimestamp(); - - if (!TimestampDifferenceExceeds(last_read, current_time, - STATS_READ_DELAY)) - return; - - last_read = current_time; - } + current_time = GetCurrentTimestamp(); + if (!TimestampDifferenceExceeds(last_read, current_time, + STATS_READ_DELAY)) + return; + last_read = current_time; pgstat_clear_snapshot(); } diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c index da768c6..3f4e93c 100644 --- a/src/backend/postmaster/pgstat.c +++ b/src/backend/postmaster/pgstat.c @@ -74,6 +74,9 @@ #define PGSTAT_STAT_INTERVAL 500 /* Minimum time between stats file * updates; in milliseconds. */ +#define PGSTAT_AVAC_INTERVAL 5000 /* Minimum time between stats file + * updates for autovacuum workers */ + #define PGSTAT_RETRY_DELAY 10 /* How long to wait between checks for * a new file; in milliseconds. */ @@ -4545,10 +4548,9 @@ backend_read_statsfile(void) /* * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL * msec before now. This indirectly ensures that the collector - * needn't write the file more often than PGSTAT_STAT_INTERVAL. In - * an autovacuum worker, however, we want a lower delay to avoid - * using stale data, so we use PGSTAT_RETRY_DELAY (since the - * number of workers is low, this shouldn't be a problem). + * needn't write the file more often than PGSTAT_STAT_INTERVAL. + * Autovacuum workers use a longer interval PGSTAT_AVAC_INTERVAL to + * avoid requesting excessively frequent rewrites of the stats. * * We don't recompute min_ts after sleeping, except in the * unlikely case that cur_ts went backwards. So we might end up @@ -4559,12 +4561,10 @@ backend_read_statsfile(void) * actually accept. */ ref_ts = cur_ts; - if (IsAutoVacuumWorkerProcess()) - min_ts = TimestampTzPlusMilliseconds(ref_ts, - -PGSTAT_RETRY_DELAY); - else - min_ts = TimestampTzPlusMilliseconds(ref_ts, - -PGSTAT_STAT_INTERVAL); + min_ts = TimestampTzPlusMilliseconds(ref_ts, + IsAutoVacuumWorkerProcess() + ? -PGSTAT_AVAC_INTERVAL + : -PGSTAT_STAT_INTERVAL); } /* diff --git a/src/backend/storage/lmgr/lwlocknames.txt b/src/backend/storage/lmgr/lwlocknames.txt index c557cb6..cd6d154 100644 --- a/src/backend/storage/lmgr/lwlocknames.txt +++ b/src/backend/storage/lmgr/lwlocknames.txt @@ -27,7 +27,7 @@ TablespaceCreateLock 19 BtreeVacuumLock 20 AddinShmemInitLock 21 AutovacuumLock 22 -AutovacuumScheduleLock 23 +# 23 is available; was formerly AutovacuumScheduleLock SyncScanLock 24 RelationMappingLock 25 AsyncCtlLock 26

view thread (38+ messages)  latest in thread

Message-ID: <20160302034537.0b1c2da7@engels>
Permalink:  ../20160302034537.0b1c2da7@engels/
Also on:    postgresql.org/message-id/20160302034537.0b1c2da7@engels

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-bugs@postgresql.org
  Cc: daveg@sonic.net, alvherre@2ndquadrant.com, jeff.janes@gmail.com, tgl@sss.pgh.pa.us, josh@agliodbs.com
  Subject: Re: BUG #13750: Autovacuum slows down with large numbers of tables. More workers makes it slower.
  In-Reply-To: <20160302034537.0b1c2da7@engels>
  References: <20151106164649.3ed185fa@engels> <20160229213350.GA332809@alvherre.pgsql> <20160302034537.0b1c2da7@engels>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox