2 18.4. Managing Kernel Resources #
4 18.4.1. Shared Memory and Semaphores
5 18.4.2. systemd RemoveIPC
6 18.4.3. Resource Limits
7 18.4.4. Linux Memory Overcommit
8 18.4.5. Linux Huge Pages
10 PostgreSQL can sometimes exhaust various operating system resource
11 limits, especially when multiple copies of the server are running on
12 the same system, or in very large installations. This section explains
13 the kernel resources used by PostgreSQL and the steps you can take to
14 resolve problems related to kernel resource consumption.
16 18.4.1. Shared Memory and Semaphores #
18 PostgreSQL requires the operating system to provide inter-process
19 communication (IPC) features, specifically shared memory and
20 semaphores. Unix-derived systems typically provide “System V” IPC,
21 “POSIX” IPC, or both. Windows has its own implementation of these
22 features and is not discussed here.
24 By default, PostgreSQL allocates a very small amount of System V shared
25 memory, as well as a much larger amount of anonymous mmap shared
26 memory. Alternatively, a single large System V shared memory region can
27 be used (see shared_memory_type). In addition a significant number of
28 semaphores, which can be either System V or POSIX style, are created at
29 server startup. Currently, POSIX semaphores are used on Linux and
30 FreeBSD systems while other platforms use System V semaphores.
32 System V IPC features are typically constrained by system-wide
33 allocation limits. When PostgreSQL exceeds one of these limits, the
34 server will refuse to start and should leave an instructive error
35 message describing the problem and what to do about it. (See also
36 Section 18.3.1.) The relevant kernel parameters are named consistently
37 across different systems; Table 18.1 gives an overview. The methods to
38 set them, however, vary. Suggestions for some platforms are given
41 Table 18.1. System V IPC Parameters
42 Name Description Values needed to run one PostgreSQL instance
43 SHMMAX Maximum size of shared memory segment (bytes) at least 1kB, but
44 the default is usually much higher
45 SHMMIN Minimum size of shared memory segment (bytes) 1
46 SHMALL Total amount of shared memory available (bytes or pages) same as
47 SHMMAX if bytes, or ceil(SHMMAX/PAGE_SIZE) if pages, plus room for
49 SHMSEG Maximum number of shared memory segments per process only 1
50 segment is needed, but the default is much higher
51 SHMMNI Maximum number of shared memory segments system-wide like SHMSEG
52 plus room for other applications
53 SEMMNI Maximum number of semaphore identifiers (i.e., sets) at least
54 ceil(num_os_semaphores / 16) plus room for other applications
55 SEMMNS Maximum number of semaphores system-wide ceil(num_os_semaphores
56 / 16) * 17 plus room for other applications
57 SEMMSL Maximum number of semaphores per set at least 17
58 SEMMAP Number of entries in semaphore map see text
59 SEMVMX Maximum value of semaphore at least 1000 (The default is often
60 32767; do not change unless necessary)
62 PostgreSQL requires a few bytes of System V shared memory (typically 48
63 bytes, on 64-bit platforms) for each copy of the server. On most modern
64 operating systems, this amount can easily be allocated. However, if you
65 are running many copies of the server or you explicitly configure the
66 server to use large amounts of System V shared memory (see
67 shared_memory_type and dynamic_shared_memory_type), it may be necessary
68 to increase SHMALL, which is the total amount of System V shared memory
69 system-wide. Note that SHMALL is measured in pages rather than bytes on
72 Less likely to cause problems is the minimum size for shared memory
73 segments (SHMMIN), which should be at most approximately 32 bytes for
74 PostgreSQL (it is usually just 1). The maximum number of segments
75 system-wide (SHMMNI) or per-process (SHMSEG) are unlikely to cause a
76 problem unless your system has them set to zero.
78 When using System V semaphores, PostgreSQL uses one semaphore per
79 allowed connection (max_connections), allowed autovacuum worker process
80 (autovacuum_worker_slots), allowed WAL sender process
81 (max_wal_senders), allowed background process (max_worker_processes),
82 etc., in sets of 16. The runtime-computed parameter num_os_semaphores
83 reports the number of semaphores required. This parameter can be viewed
84 before starting the server with a postgres command like:
85 $ postgres -D $PGDATA -C num_os_semaphores
87 Each set of 16 semaphores will also contain a 17th semaphore which
88 contains a “magic number”, to detect collision with semaphore sets used
89 by other applications. The maximum number of semaphores in the system
90 is set by SEMMNS, which consequently must be at least as high as
91 num_os_semaphores plus one extra for each set of 16 required semaphores
92 (see the formula in Table 18.1). The parameter SEMMNI determines the
93 limit on the number of semaphore sets that can exist on the system at
94 one time. Hence this parameter must be at least ceil(num_os_semaphores
95 / 16). Lowering the number of allowed connections is a temporary
96 workaround for failures, which are usually confusingly worded “No space
97 left on device”, from the function semget.
99 In some cases it might also be necessary to increase SEMMAP to be at
100 least on the order of SEMMNS. If the system has this parameter (many do
101 not), it defines the size of the semaphore resource map, in which each
102 contiguous block of available semaphores needs an entry. When a
103 semaphore set is freed it is either added to an existing entry that is
104 adjacent to the freed block or it is registered under a new map entry.
105 If the map is full, the freed semaphores get lost (until reboot).
106 Fragmentation of the semaphore space could over time lead to fewer
107 available semaphores than there should be.
109 Various other settings related to “semaphore undo”, such as SEMMNU and
110 SEMUME, do not affect PostgreSQL.
112 When using POSIX semaphores, the number of semaphores needed is the
113 same as for System V, that is one semaphore per allowed connection
114 (max_connections), allowed autovacuum worker process
115 (autovacuum_worker_slots), allowed WAL sender process
116 (max_wal_senders), allowed background process (max_worker_processes),
117 etc. On the platforms where this option is preferred, there is no
118 specific kernel limit on the number of POSIX semaphores.
121 The default shared memory settings are usually good enough,
122 unless you have set shared_memory_type to sysv. System V
123 semaphores are not used on this platform.
125 The default IPC settings can be changed using the sysctl or
126 loader interfaces. The following parameters can be set using
129 # sysctl kern.ipc.shmall=32768
130 # sysctl kern.ipc.shmmax=134217728
132 To make these settings persist over reboots, modify
135 If you have set shared_memory_type to sysv, you might also want
136 to configure your kernel to lock System V shared memory into RAM
137 and prevent it from being paged out to swap. This can be
138 accomplished using the sysctl setting kern.ipc.shm_use_phys.
140 If running in a FreeBSD jail, you should set its sysvshm
141 parameter to new, so that it has its own separate System V
142 shared memory namespace. (Before FreeBSD 11.0, it was necessary
143 to enable shared access to the host's IPC namespace from jails,
144 and take measures to avoid collisions.)
147 The default shared memory settings are usually good enough,
148 unless you have set shared_memory_type to sysv. However, you
149 will need to increase kern.ipc.semmni and kern.ipc.semmns, as
150 NetBSD's default settings for these are unworkably small.
152 IPC parameters can be adjusted using sysctl, for example:
154 # sysctl -w kern.ipc.semmni=100
156 To make these settings persist over reboots, modify
159 If you have set shared_memory_type to sysv, you might also want
160 to configure your kernel to lock System V shared memory into RAM
161 and prevent it from being paged out to swap. This can be
162 accomplished using the sysctl setting kern.ipc.shm_use_phys.
165 The default shared memory settings are usually good enough,
166 unless you have set shared_memory_type to sysv. However, you
167 will need to increase kern.seminfo.semmni and
168 kern.seminfo.semmns, as OpenBSD's default settings for these are
171 IPC parameters can be adjusted using sysctl, for example:
173 # sysctl kern.seminfo.semmni=100
175 To make these settings persist over reboots, modify
179 The default shared memory settings are usually good enough,
180 unless you have set shared_memory_type to sysv, and even then
181 only on older kernel versions that shipped with low defaults.
182 System V semaphores are not used on this platform.
184 The shared memory size settings can be changed via the sysctl
185 interface. For example, to allow 16 GB:
187 $ sysctl -w kernel.shmmax=17179869184
188 $ sysctl -w kernel.shmall=4194304
190 To make these settings persist over reboots, see
194 The default shared memory and semaphore settings are usually
195 good enough, unless you have set shared_memory_type to sysv.
197 The recommended method for configuring shared memory in macOS is
198 to create a file named /etc/sysctl.conf, containing variable
201 kern.sysv.shmmax=4194304
205 kern.sysv.shmall=1024
207 Note that in some macOS versions, all five shared-memory
208 parameters must be set in /etc/sysctl.conf, else the values will
211 SHMMAX can only be set to a multiple of 4096.
213 SHMALL is measured in 4 kB pages on this platform.
215 It is possible to change all but SHMMNI on the fly, using
216 sysctl. But it's still best to set up your preferred values via
217 /etc/sysctl.conf, so that the values will be kept across
222 The default shared memory and semaphore settings are usually
223 good enough for most PostgreSQL applications. Solaris defaults
224 to a SHMMAX of one-quarter of system RAM. To further adjust this
225 setting, use a project setting associated with the postgres
226 user. For example, run the following as root:
228 projadd -c "PostgreSQL DB User" -K "project.max-shm-memory=(privileged,8GB,deny)
229 " -U postgres -G postgres user.postgres
231 This command adds the user.postgres project and sets the shared
232 memory maximum for the postgres user to 8GB, and takes effect
233 the next time that user logs in, or when you restart PostgreSQL
234 (not reload). The above assumes that PostgreSQL is run by the
235 postgres user in the postgres group. No server reboot is
238 Other recommended kernel setting changes for database servers
239 which will have a large number of connections are:
241 project.max-shm-ids=(priv,32768,deny)
242 project.max-sem-ids=(priv,4096,deny)
243 project.max-msg-ids=(priv,4096,deny)
245 Additionally, if you are running PostgreSQL inside a zone, you
246 may need to raise the zone resource usage limits as well. See
247 "Chapter2: Projects and Tasks" in the System Administrator's
248 Guide for more information on projects and prctl.
250 18.4.2. systemd RemoveIPC #
252 If systemd is in use, some care must be taken that IPC resources
253 (including shared memory) are not prematurely removed by the operating
254 system. This is especially of concern when installing PostgreSQL from
255 source. Users of distribution packages of PostgreSQL are less likely to
256 be affected, as the postgres user is then normally created as a system
259 The setting RemoveIPC in logind.conf controls whether IPC objects are
260 removed when a user fully logs out. System users are exempt. This
261 setting defaults to on in stock systemd, but some operating system
262 distributions default it to off.
264 A typical observed effect when this setting is on is that shared memory
265 objects used for parallel query execution are removed at apparently
266 random times, leading to errors and warnings while attempting to open
267 and remove them, like
268 WARNING: could not remove shared memory segment "/PostgreSQL.1450751626": No su
271 Different types of IPC objects (shared memory vs. semaphores, System V
272 vs. POSIX) are treated slightly differently by systemd, so one might
273 observe that some IPC resources are not removed in the same way as
274 others. But it is not advisable to rely on these subtle differences.
276 A “user logging out” might happen as part of a maintenance job or
277 manually when an administrator logs in as the postgres user or
278 something similar, so it is hard to prevent in general.
280 What is a “system user” is determined at systemd compile time from the
281 SYS_UID_MAX setting in /etc/login.defs.
283 Packaging and deployment scripts should be careful to create the
284 postgres user as a system user by using useradd -r, adduser --system,
287 Alternatively, if the user account was created incorrectly or cannot be
288 changed, it is recommended to set
291 in /etc/systemd/logind.conf or another appropriate configuration file.
295 At least one of these two things has to be ensured, or the PostgreSQL
296 server will be very unreliable.
298 18.4.3. Resource Limits #
300 Unix-like operating systems enforce various kinds of resource limits
301 that might interfere with the operation of your PostgreSQL server. Of
302 particular importance are limits on the number of processes per user,
303 the number of open files per process, and the amount of memory
304 available to each process. Each of these have a “hard” and a “soft”
305 limit. The soft limit is what actually counts but it can be changed by
306 the user up to the hard limit. The hard limit can only be changed by
307 the root user. The system call setrlimit is responsible for setting
308 these parameters. The shell's built-in command ulimit (Bourne shells)
309 or limit (csh) is used to control the resource limits from the command
310 line. On BSD-derived systems the file /etc/login.conf controls the
311 various resource limits set during login. See the operating system
312 documentation for details. The relevant parameters are maxproc,
313 openfiles, and datasize. For example:
321 (-cur is the soft limit. Append -max to set the hard limit.)
323 Kernels can also have system-wide limits on some resources.
324 * On Linux the kernel parameter fs.file-max determines the maximum
325 number of open files that the kernel will support. It can be
326 changed with sysctl -w fs.file-max=N. To make the setting persist
327 across reboots, add an assignment in /etc/sysctl.conf. The maximum
328 limit of files per process is fixed at the time the kernel is
329 compiled; see /usr/src/linux/Documentation/proc.txt for more
332 The PostgreSQL server uses one process per connection so you should
333 provide for at least as many processes as allowed connections, in
334 addition to what you need for the rest of your system. This is usually
335 not a problem but if you run several servers on one machine things
338 The factory default limit on open files is often set to “socially
339 friendly” values that allow many users to coexist on a machine without
340 using an inappropriate fraction of the system resources. If you run
341 many servers on a machine this is perhaps what you want, but on
342 dedicated servers you might want to raise this limit.
344 On the other side of the coin, some systems allow individual processes
345 to open large numbers of files; if more than a few processes do so then
346 the system-wide limit can easily be exceeded. If you find this
347 happening, and you do not want to alter the system-wide limit, you can
348 set PostgreSQL's max_files_per_process configuration parameter to limit
349 the consumption of open files.
351 Another kernel limit that may be of concern when supporting large
352 numbers of client connections is the maximum socket connection queue
353 length. If more than that many connection requests arrive within a very
354 short period, some may get rejected before the PostgreSQL server can
355 service the requests, with those clients receiving unhelpful connection
356 failure errors such as “Resource temporarily unavailable” or
357 “Connection refused”. The default queue length limit is 128 on many
358 platforms. To raise it, adjust the appropriate kernel parameter via
359 sysctl, then restart the PostgreSQL server. The parameter is variously
360 named net.core.somaxconn on Linux, kern.ipc.soacceptqueue on newer
361 FreeBSD, and kern.ipc.somaxconn on macOS and other BSD variants.
363 18.4.4. Linux Memory Overcommit #
365 The default virtual memory behavior on Linux is not optimal for
366 PostgreSQL. Because of the way that the kernel implements memory
367 overcommit, the kernel might terminate the PostgreSQL postmaster (the
368 supervisor server process) if the memory demands of either PostgreSQL
369 or another process cause the system to run out of virtual memory.
371 If this happens, you will see a kernel message that looks like this
372 (consult your system documentation and configuration on where to look
374 Out of Memory: Killed process 12345 (postgres).
376 This indicates that the postgres process has been terminated due to
377 memory pressure. Although existing database connections will continue
378 to function normally, no new connections will be accepted. To recover,
379 PostgreSQL will need to be restarted.
381 One way to avoid this problem is to run PostgreSQL on a machine where
382 you can be sure that other processes will not run the machine out of
383 memory. If memory is tight, increasing the swap space of the operating
384 system can help avoid the problem, because the out-of-memory (OOM)
385 killer is invoked only when physical memory and swap space are
388 If PostgreSQL itself is the cause of the system running out of memory,
389 you can avoid the problem by changing your configuration. In some
390 cases, it may help to lower memory-related configuration parameters,
391 particularly shared_buffers, work_mem, and hash_mem_multiplier. In
392 other cases, the problem may be caused by allowing too many connections
393 to the database server itself. In many cases, it may be better to
394 reduce max_connections and instead make use of external
395 connection-pooling software.
397 It is possible to modify the kernel's behavior so that it will not
398 “overcommit” memory. Although this setting will not prevent the OOM
399 killer from being invoked altogether, it will lower the chances
400 significantly and will therefore lead to more robust system behavior.
401 This is done by selecting strict overcommit mode via sysctl:
402 sysctl -w vm.overcommit_memory=2
404 or placing an equivalent entry in /etc/sysctl.conf. You might also wish
405 to modify the related setting vm.overcommit_ratio. For details see the
406 kernel documentation file
407 https://www.kernel.org/doc/Documentation/vm/overcommit-accounting.
409 Another approach, which can be used with or without altering
410 vm.overcommit_memory, is to set the process-specific OOM score
411 adjustment value for the postmaster process to -1000, thereby
412 guaranteeing it will not be targeted by the OOM killer. The simplest
413 way to do this is to execute
414 echo -1000 > /proc/self/oom_score_adj
416 in the PostgreSQL startup script just before invoking postgres. Note
417 that this action must be done as root, or it will have no effect; so a
418 root-owned startup script is the easiest place to do it. If you do
419 this, you should also set these environment variables in the startup
420 script before invoking postgres:
421 export PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
422 export PG_OOM_ADJUST_VALUE=0
424 These settings will cause postmaster child processes to run with the
425 normal OOM score adjustment of zero, so that the OOM killer can still
426 target them at need. You could use some other value for
427 PG_OOM_ADJUST_VALUE if you want the child processes to run with some
428 other OOM score adjustment. (PG_OOM_ADJUST_VALUE can also be omitted,
429 in which case it defaults to zero.) If you do not set
430 PG_OOM_ADJUST_FILE, the child processes will run with the same OOM
431 score adjustment as the postmaster, which is unwise since the whole
432 point is to ensure that the postmaster has a preferential setting.
434 18.4.5. Linux Huge Pages #
436 Using huge pages reduces overhead when using large contiguous chunks of
437 memory, as PostgreSQL does, particularly when using large values of
438 shared_buffers. To use this feature in PostgreSQL you need a kernel
439 with CONFIG_HUGETLBFS=y and CONFIG_HUGETLB_PAGE=y. You will also have
440 to configure the operating system to provide enough huge pages of the
441 desired size. The runtime-computed parameter
442 shared_memory_size_in_huge_pages reports the number of huge pages
443 required. This parameter can be viewed before starting the server with
444 a postgres command like:
445 $ postgres -D $PGDATA -C shared_memory_size_in_huge_pages
447 $ grep ^Hugepagesize /proc/meminfo
448 Hugepagesize: 2048 kB
449 $ ls /sys/kernel/mm/hugepages
450 hugepages-1048576kB hugepages-2048kB
452 In this example the default is 2MB, but you can also explicitly request
453 either 2MB or 1GB with huge_page_size to adapt the number of pages
454 calculated by shared_memory_size_in_huge_pages. While we need at least
455 3170 huge pages in this example, a larger setting would be appropriate
456 if other programs on the machine also need huge pages. We can set this
458 # sysctl -w vm.nr_hugepages=3170
460 Don't forget to add this setting to /etc/sysctl.conf so that it is
461 reapplied after reboots. For non-default huge page sizes, we can
463 # echo 3170 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
465 It is also possible to provide these settings at boot time using kernel
466 parameters such as hugepagesz=2M hugepages=3170.
468 Sometimes the kernel is not able to allocate the desired number of huge
469 pages immediately due to fragmentation, so it might be necessary to
470 repeat the command or to reboot. (Immediately after a reboot, most of
471 the machine's memory should be available to convert into huge pages.)
472 To verify the huge page allocation situation for a given size, use:
473 $ cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
475 It may also be necessary to give the database server's operating system
476 user permission to use huge pages by setting vm.hugetlb_shm_group via
477 sysctl, and/or give permission to lock memory with ulimit -l.
479 The default behavior for huge pages in PostgreSQL is to use them when
480 possible, with the system's default huge page size, and to fall back to
481 normal pages on failure. To enforce the use of huge pages, you can set
482 huge_pages to on in postgresql.conf. Note that with this setting
483 PostgreSQL will fail to start if not enough huge pages are available.
485 For a detailed description of the Linux huge pages feature have a look
486 at https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt.