Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1ab5Ej-0003Zy-4B for pgsql-bugs@arkaria.postgresql.org; Wed, 02 Mar 2016 11:46:37 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84) (envelope-from ) id 1ab5Ei-00078c-Hf for pgsql-bugs@arkaria.postgresql.org; Wed, 02 Mar 2016 11:46:36 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ab5E2-0006OA-4b for pgsql-bugs@postgresql.org; Wed, 02 Mar 2016 11:45:54 +0000 Received: from c.mail.sonic.net ([64.142.111.80]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ab5Dv-0005jt-2x for pgsql-bugs@postgresql.org; Wed, 02 Mar 2016 11:45:52 +0000 Received: from engels (162-236-13-58.lightspeed.sntcca.sbcglobal.net [162.236.13.58]) (authenticated bits=0) by c.mail.sonic.net (8.15.1/8.15.1) with ESMTPSA id u22BjY1Z002174 (version=TLSv1.2 cipher=DHE-RSA-AES128-SHA256 bits=128 verify=NOT); Wed, 2 Mar 2016 03:45:35 -0800 Date: Wed, 2 Mar 2016 03:45:37 -0800 From: David Gould To: Alvaro Herrera Cc: Jeff Janes , Tom Lane , Pg Bugs , Josh Berkus Subject: Re: BUG #13750: Autovacuum slows down with large numbers of tables. More workers makes it slower. Message-ID: <20160302034537.0b1c2da7@engels> In-Reply-To: <20160229213350.GA332809@alvherre.pgsql> References: <20151106164649.3ed185fa@engels> <20160229213350.GA332809@alvherre.pgsql> X-Mailer: Claws Mail 3.11.1 (GTK+ 2.24.23; x86_64-pc-linux-gnu) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="MP_/K0WCuxlLRGtJlU02BRdoRvs" X-Sonic-CAuth: UmFuZG9tSVbGbD7u+aeFw0G4w3kq5lgBEZGx1fjQ9GzYfkty0zAeI8hM29ham5RpeoRnYb9P/GjBzOWvWAlf2UZDUGctpn0Q X-Sonic-ID: C;atxmRmzg5RGyRomKr5/Qwg== M;hs6ZRmzg5RGyRomKr5/Qwg== X-Spam-Flag: No X-Sonic-Spam-Details: 0.0/5.0 by cerberusd X-Pg-Spam-Score: -2.6 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org --MP_/K0WCuxlLRGtJlU02BRdoRvs Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Content-Disposition: inline On Mon, 29 Feb 2016 18:33:50 -0300 Alvaro Herrera 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. --MP_/K0WCuxlLRGtJlU02BRdoRvs Content-Type: text/x-patch Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename=autovacuum_contention_0301.patch 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 --MP_/K0WCuxlLRGtJlU02BRdoRvs Content-Type: text/plain Content-Disposition: inline Content-Transfer-Encoding: 8bit MIME-Version: 1.0 -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs --MP_/K0WCuxlLRGtJlU02BRdoRvs--