Laurenz Albe: How to deal with slow shutdown in PostgreSQL


© Laurenz Albe 2025
If you have to restart the PostgreSQL server, you often want to keep the down time as short as possible. Starting the server is usually fast, but shutdown can be slow. In this article I describe why there can be a slow shutdown and what you can do to speed it up.
PostgreSQL shutdown modes
We have to understand what happens during a PostgreSQL shutdown. This varies depending on the shutdown mode, which is determined by the signal sent to the postmaster process:
- smart shutdown (signal
SIGTERM): don't allow any new connections, wait for the last client to disconnect, then shut down cleanly - fast shutdown (signal
SIGINT): terminate all existing connections and shut down cleanly - immediate shutdown (signal
SIGQUIT): kill all processes and exit without a clean shutdown
“Smart” shutdown clearly is not an option for a fast restart. “Immediate” mode is also not a good idea: the server will terminate quickly, but PostgreSQL will have to perform crash recovery during the nest start, which can also take a long time. (This is a typical “false friend” for Oracle users: there, an IMMEDIATE shutdown is what a fast shutdown is in PostgreSQL.)
During a clean shutdown, PostgreSQL performs a checkpoint to flush all dirty (modified) pages from shared buffers to disk. That is what makes a checkpoint slow: the bigger shared buffers is and the more buffers are dirty, the slower the shutdown will be.
Speeding up the final checkpoint to combat slow shutdown
To speed up the shutdown checkpoint as much as possible, we have to make sure that there are as few dirty buffers as possible. There are never as few dirty buffers as right after a checkpoint. Consequently, a shutdown will be fast if we do it right after a checkpoint. Moreover, that checkpoint shouldn't be a (default) “spread” checkpoint, but a “fast” one. The SQL statement CHECKPOINT triggers such a checkpoint, so you could run the following for a fast restart:
# could take long, but the database is still up psql -c CHECKPOINT # should be fast pg_ctl restart
UNLOGGED tables can still cause a slow shutdown
Even with the above trick, shutting down PostgreSQL could still take a long time if you have big UNLOGGED tables. Such tables don't write WAL for data modifications. Skipping WAL speeds up data modifications, but prevents recovery after a crash: UNLOGGED tables will be empty after crash recovery. Since UNLOGGED tables are not crash-safe anyway, PostgreSQL sees no need to flush their dirty data to disk during a normal checkpoint. But since the data in UNLOGGED tables survive a clean shutdown, the shutdown checkpoint has to flush these data to disk.
Because of that, triggering a normal checkpoint right before recovery is not enough. The shutdown at checkpoint would still be slow. I can show that with the following experiment (which assumes shared_buffers to be 2GB or more):
CREATE UNLOGGED TABLE large ( id bigint GENERATED ALWAYS AS IDENTITY, s text STORAGE EXTERNAL ); INSERT INTO large (s) SELECT repeat('0123456789', 100) FROM generate_series(1, 1000000); SELECT pg_size_pretty(pg_table_size('large')); pg_size_pretty ════════════════ 1116 MBIf we shut down PostgreSQL as described in the previous section (and have log_checkpoints = on), we will find the following in the log:
LOG: checkpoint starting: immediate force wait LOG: checkpoint complete: wrote 1 buffers (0.0%); [...] LOG: received fast shutdown request LOG: aborting any active transactions LOG: background worker "logical replication launcher" (PID 38137) exited with exit code 1 LOG: shutting down LOG: checkpoint starting: shutdown immediate LOG: checkpoint complete: wrote 142902 buffers (54.5%); [...] LOG: database system is shut down
The manually started checkpoint didn't do anything, and we still have a slow shutdown.
How to avoid a slow shutdown with UNLOGGED tables
Studying the source code reveals that PostgreSQL checkpoints flush dirty pages from UNLOGGED tables to disk in four cases:
-
- during shutdown
- from PostgreSQL v19 on, if you run
CHECKPOINT (FLUSH_UNLOGGED) - at the end of recovery, when PostgreSQL “promotes” the database to read-write mode
- at the beginning of
CREATE DATABASEwith the traditionalFILE_COPYstrategy - at the beginning of
ALTER DATABASE ... SET TABLESPACE
So for PostgreSQL v19 and better, the solution is obvious: we just have to perform the explicit checkpoint with the FLUSH_UNLOGGED option. But we want a solution for older versions as well, so let's take a closer look.
The reason for the last two points is that they copy or move data by manipulating the data files, so the files must me up to date. We want to avoid the first point, and we cannot use the second point because we cannot get a database into recovery mode without restarting it. That leaves the last two methods, and the third one is more convenient, as it does not require the creation of a tablespace. So we can force a checkpoint that flushes UNLOGGED tables to disk as follows:
CREATE DATABASE dummy TEMPLATE template0 STRATEGY FILE_COPY; DROP DATABASE dummy;
The STRATEGY option was introduced in PostgreSQL v15, which changed the default strategy to WAL_LOG. If you are using a PostgreSQL version older than v15, simply omit the STRATEGY option. I used template0 as template database, because it is always empty, so CREATE DATABASE and DROP DATABASE should be as fast as possible.
Testing if our trick to avoid slow shutdown with UNLOGGED tables works
After we restart our database, we have to make sure that our test table is in shared buffers and that all buffers are dirty. The easiest way to do that is to take a row lock on all rows of the table:
SELECT id FROM large FOR NO KEY UPDATE;
Now we are ready for a fast shutdown. For convenience, we will use the utilities createdb and dropdb:
# omit the --strategy option before v15 createdb --strategy=file_copy dummy dropdb dummy pg_ctl stop
The log confirms that our trick worked:
LOG: checkpoint starting: immediate force wait flush-all LOG: checkpoint complete: wrote 142864 buffers (54.5%); [...] LOG: checkpoint starting: immediate force wait LOG: checkpoint complete: wrote 0 buffers (0.0%); [...] LOG: checkpoint starting: immediate force wait LOG: checkpoint complete: wrote 3 buffers (0.0%); [...] LOG: received fast shutdown request LOG: aborting any active transactions LOG: background worker "logical replication launcher" (PID 1572) exited with exit code 1 LOG: shutting down LOG: checkpoint starting: shutdown immediate LOG: checkpoint complete: wrote 2 buffers (0.0%); [...] LOG: database system is shut down
There are two additional checkpoints: one is from the end of the CREATE DATABASE statement, the other from DROP TABLE. But all checkpoints except the first one had very little to do and were fast.
Conclusion
We can avoid slow shutdowns by explicitly running a checkpoint right before shutting down the database. If there are large unlogged tables, that trick does not work, and we have to use a more advanced trick to make PostgreSQL flush all dirty buffers to disk.
Special thanks to my co-worker Bernd Helmle for getting me on the right track with this problem! Also, thanks to Christoph Berg for implementing CHECKPOINT (FLUSH_UNLOGGED) for v19, which provides a simple solution for unlogged tables.
The post How to deal with slow shutdown in PostgreSQL appeared first on CYBERTEC PostgreSQL | Services & Support.
原文:https://www.a8q9.cn/en/article/laurenz-albe-how-to-deal-with-slow-shutdown-in-postgresql-a96d66.html