From ec079f1ccd093d0a2363adbbcb92460b4996adc0 Mon Sep 17 00:00:00 2001 From: Andrew Kim Date: Tue, 1 Dec 2026 20:19:55 +0000 Subject: [PATCH v1] Add numa_nodes to restrict the server to a set of NUMA nodes On a machine with more than one processor socket, letting an instance spread over every NUMA node can cost more than half of its throughput. Measured with HammerDB TPROC-C on a 2-socket, 6-node Xeon, confining the server to the nodes of a single socket raised throughput by 116% at 1536 warehouses and by 121% at 250 warehouses. On a single-socket, 3-node machine the same confinement was worth 36%, so this is not only a multi-socket effect, though it is much larger across sockets. The cost is remote memory latency rather than bandwidth. In the unconfined case DRAM Bound is 20.8% of clockticks and interconnect utilisation averages 14%; confining the server to one socket takes interconnect utilisation to zero, halves DRAM Bound to 10.7%, raises the count of local memory accesses more than eightfold, and reduces cycles per transaction by 24% while leaving instructions per transaction essentially unchanged. It removes stalls rather than work. No memory controller exceeded 12% of its peak bandwidth in any configuration, and cache-to-cache transfers per transaction barely moved, so neither bandwidth saturation nor cache line contention explains the difference. This adds a numa_nodes parameter. When it is set, the postmaster restricts its CPU affinity to the CPUs of the listed nodes, and every child process inherits that affinity when it is forked. The parameter is empty by default, in which case no NUMA policy is applied and behaviour is unchanged. It can only be set at server start, and only in a build configured with --with-libnuma. The value uses the same node-list syntax as the numactl --membind option. Only CPU affinity is set. Once the CPUs are confined, the default first-touch policy allocates memory on the nodes those CPUs belong to, so an explicit memory policy on top of it adds nothing: confining the CPUs alone came within 1.2% of confining CPUs and memory together, while confining memory alone and leaving the CPUs free was no better than applying no policy at all. Placement of shared memory within a node set is a separate question, and a more careful one than a single interleave call can answer. The policy is applied once, before the first child is forked. sched_setaffinity() affects only the calling process, so a policy applied later would reach only backends forked after it, which on a workload that uses a connection pool means none of them; the alternative, one process rewriting another process's CPU mask, is not something the server should be doing. The same throughput can be obtained today by launching the server under numactl, and in measurements the two are indistinguishable. What this parameter adds is that the placement is stated where the rest of the configuration lives, is visible in pg_settings, is validated against the running system's topology at startup with an error that names the valid nodes, and applies however the server was started rather than only when an external wrapper was used to launch it. It is deliberately a mechanism and not a policy. It does not try to choose a node set, because the best choice depends on the socket topology, on where network interrupts are handled, and on the workload; no rule covering all three survived measurement. In particular, excluding the node that handles network interrupts helped on one machine and hurt on another, and within a single socket the best node count was not monotonic. --- doc/src/sgml/config.sgml | 49 +++++ src/backend/postmaster/postmaster.c | 7 + src/backend/storage/ipc/Makefile | 1 + src/backend/storage/ipc/meson.build | 1 + src/backend/storage/ipc/numa_policy.c | 191 ++++++++++++++++++ src/backend/utils/misc/guc_parameters.dat | 8 + src/backend/utils/misc/guc_tables.c | 1 + src/backend/utils/misc/postgresql.conf.sample | 2 + src/include/storage/numa_policy.h | 24 +++ src/test/modules/test_misc/meson.build | 1 + .../modules/test_misc/t/016_numa_nodes.pl | 83 ++++++++ 11 files changed, 368 insertions(+) create mode 100644 src/backend/storage/ipc/numa_policy.c create mode 100644 src/include/storage/numa_policy.h create mode 100644 src/test/modules/test_misc/t/016_numa_nodes.pl diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 886e8c44847..f3d0c88364e 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -1841,6 +1841,55 @@ include_dir 'conf.d' + + numa_nodes (string) + + numa_nodes configuration parameter + + + + + Restricts the server to the given NUMA nodes. The postmaster confines + its CPU affinity to the CPUs of these nodes, and every child process + inherits that affinity when it is forked. + + + The value uses the same node-list syntax as the + option of numactl, for + example 0,1 or 0-3. An empty + value, the default, applies no NUMA policy. This parameter can only + be set at server start, and only in a server built with + . + + + No memory policy is applied. Once the CPUs are confined, the default + first-touch policy allocates memory on the nodes those CPUs belong + to, so a separate memory policy is not required to keep allocations + local. + + + On a machine with more than one processor socket, list the nodes that + belong to a single socket. Spreading an instance across sockets costs + much more than the additional CPUs are worth, because the backends + then satisfy a large share of their memory accesses from the other + socket; adding the CPUs of a second socket can reduce throughput + rather than increase it. The mapping from nodes to sockets is + reported by numactl --hardware and by + lscpu. + + + On a single-socket machine the choice of nodes matters much less, and + fewer nodes is not reliably better, so measure rather than assume. + Whether the node that handles network interrupts should be included is + also best decided by measurement. + + + The pg_shmem_allocations_numa view can be + used to see where shared memory actually ended up. + + + + huge_pages (enum) diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 34d1c8ae3f6..375f5ada759 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -113,6 +113,7 @@ #include "storage/fd.h" #include "storage/io_worker.h" #include "storage/ipc.h" +#include "storage/numa_policy.h" #include "storage/pmsignal.h" #include "storage/proc.h" #include "storage/shmem_internal.h" @@ -1007,6 +1008,12 @@ PostmasterMain(int argc, char *argv[]) ExitPostmaster(0); } + /* + * Apply the NUMA policy requested by "numa_nodes" before any child + * process is forked, so that every process inherits the affinity. + */ + NumaPolicyApplyCpuAffinity(); + /* * Set up shared memory and semaphores. * diff --git a/src/backend/storage/ipc/Makefile b/src/backend/storage/ipc/Makefile index f71653bbe48..3535af022a1 100644 --- a/src/backend/storage/ipc/Makefile +++ b/src/backend/storage/ipc/Makefile @@ -16,6 +16,7 @@ OBJS = \ ipc.o \ ipci.o \ latch.o \ + numa_policy.o \ pmsignal.o \ procarray.o \ procsignal.o \ diff --git a/src/backend/storage/ipc/meson.build b/src/backend/storage/ipc/meson.build index b8c31e29967..a971f12b4b2 100644 --- a/src/backend/storage/ipc/meson.build +++ b/src/backend/storage/ipc/meson.build @@ -8,6 +8,7 @@ backend_sources += files( 'ipc.c', 'ipci.c', 'latch.c', + 'numa_policy.c', 'pmsignal.c', 'procarray.c', 'procsignal.c', diff --git a/src/backend/storage/ipc/numa_policy.c b/src/backend/storage/ipc/numa_policy.c new file mode 100644 index 00000000000..e0317f8d0fb --- /dev/null +++ b/src/backend/storage/ipc/numa_policy.c @@ -0,0 +1,191 @@ +/*------------------------------------------------------------------------- + * + * numa_policy.c + * Restrict the server to a set of NUMA nodes. + * + * On a machine with more than one processor socket, letting an instance + * spread over every NUMA node can cost a large fraction of its throughput. + * The cost is in remote memory latency rather than in bandwidth, so adding + * the CPUs of a second socket can reduce throughput rather than increase it. + * + * When "numa_nodes" is set, the postmaster restricts its CPU affinity to the + * CPUs of the listed nodes, and every child process inherits that affinity + * when it is forked. + * + * Only CPU affinity is set, and that is deliberate: once the CPUs are + * confined, the default first-touch policy allocates memory on the nodes + * those CPUs belong to, so an explicit memory policy on top of it is + * redundant. Placement of shared memory within a node set is a separate + * question, and a more careful one than a single interleave call can answer. + * + * The policy is applied once, before the first child exists. + * sched_setaffinity() affects only the calling process, so a policy applied + * later would reach only backends forked after it - which, on a workload that + * uses a connection pool, means none of them - and the alternative of one + * process rewriting another process's CPU mask is not something the server + * should be doing. + * + * Nothing here monitors the running system. Deciding how many nodes a + * workload should occupy, and moving it when that changes, is the kernel's + * job; this is only a way to tell the kernel what the server may use. + * + * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * IDENTIFICATION + * src/backend/storage/ipc/numa_policy.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#ifdef USE_LIBNUMA +#include +#endif + +#include "miscadmin.h" +#include "storage/numa_policy.h" + +/* + * GUC: the NUMA nodes the server may use, in the same syntax numactl accepts + * for --membind (for example "0,1" or "0-3"). Empty means no NUMA policy is + * applied, which is the default and leaves behaviour unchanged. + */ +char *numa_nodes = ""; + +#ifdef USE_LIBNUMA + +/* + * parse_numa_nodes - parse the GUC string into a node mask. + * + * Returns NULL if the value is empty, does not parse, or selects no node that + * this process is permitted to use. The caller frees the result with + * numa_bitmask_free(). + */ +static struct bitmask * +parse_numa_nodes(const char *str) +{ + struct bitmask *nodes; + + if (str == NULL || str[0] == '\0') + return NULL; + + /* + * numa_parse_nodestring() implements exactly the syntax of numactl's + * --membind, and intersects the result with the nodes this process is + * allowed to use, so a value naming a node outside an enclosing cpuset is + * reported as invalid rather than silently ignored. + */ + nodes = numa_parse_nodestring(str); + if (nodes == NULL) + return NULL; + + if (numa_bitmask_weight(nodes) == 0) + { + numa_bitmask_free(nodes); + return NULL; + } + + return nodes; +} + +#endif /* USE_LIBNUMA */ + +/* + * check_numa_nodes - GUC check hook for "numa_nodes". + */ +bool +check_numa_nodes(char **newval, void **extra, GucSource source) +{ + if (*newval == NULL || (*newval)[0] == '\0') + return true; /* no policy requested */ + +#ifdef USE_LIBNUMA + { + struct bitmask *nodes; + + if (numa_available() == -1) + { + GUC_check_errdetail("NUMA support is not available on this system."); + return false; + } + + nodes = parse_numa_nodes(*newval); + if (nodes == NULL) + { + GUC_check_errdetail("\"numa_nodes\" must be a list of NUMA nodes this server may use, for example \"0,1\" or \"0-3\"."); + GUC_check_errhint("This system has NUMA nodes 0 to %d.", + numa_max_node()); + return false; + } + + numa_bitmask_free(nodes); + return true; + } +#else + GUC_check_errdetail("\"numa_nodes\" requires a server built with --with-libnuma."); + return false; +#endif +} + +/* + * NumaPolicyApplyCpuAffinity - restrict the postmaster to the CPUs of the + * configured nodes. + * + * Must be called from the postmaster before any child process is forked, so + * that children inherit the affinity. + */ +void +NumaPolicyApplyCpuAffinity(void) +{ +#ifdef USE_LIBNUMA + struct bitmask *nodes; + + if (numa_nodes == NULL || numa_nodes[0] == '\0') + return; + + Assert(!IsUnderPostmaster); + + if (numa_available() == -1) + { + ereport(LOG, + errmsg("NUMA support is not available, ignoring \"numa_nodes\"")); + return; + } + + nodes = parse_numa_nodes(numa_nodes); + if (nodes == NULL) + return; /* rejected by check_numa_nodes() already */ + + /* + * numa_run_on_node_mask() confines the calling process to the CPUs of the + * given nodes, and honours an enclosing cpuset rather than overriding it. + */ + if (numa_run_on_node_mask(nodes) != 0) + ereport(WARNING, + errmsg("could not restrict the server to NUMA nodes \"%s\": %m", + numa_nodes)); + else + { + struct bitmask *cpus = numa_allocate_cpumask(); + int ncpus = 0; + + /* + * Report the affinity that is actually in effect. Do not use + * numa_num_task_cpus() here: it reports how many CPUs an enclosing + * cpuset permits, not how many the call above left us with, so on a + * machine with no cpuset restriction it reports every CPU present. + */ + if (numa_sched_getaffinity(0, cpus) > 0) + ncpus = numa_bitmask_weight(cpus); + numa_free_cpumask(cpus); + + ereport(LOG, + errmsg("server restricted to %d CPUs of NUMA nodes \"%s\"", + ncpus, numa_nodes), + errdetail("Child processes inherit this affinity.")); + } + + numa_bitmask_free(nodes); +#endif +} diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat index 184fcf49080..7b2d38dbd8f 100644 --- a/src/backend/utils/misc/guc_parameters.dat +++ b/src/backend/utils/misc/guc_parameters.dat @@ -2319,6 +2319,14 @@ max => 'INT_MAX', }, +{ name => 'numa_nodes', type => 'string', context => 'PGC_POSTMASTER', group => 'RESOURCES_MEM', + short_desc => 'Restricts the server to the given NUMA nodes.', + long_desc => 'The postmaster confines its CPU affinity to the CPUs of these nodes, and every child process inherits it. An empty value applies no NUMA policy. The syntax is that of the numactl --membind option, for example 0,1 or 0-3.', + variable => 'numa_nodes', + boot_val => '""', + check_hook => 'check_numa_nodes', +}, + { name => 'oauth_validator_libraries', type => 'string', context => 'PGC_SIGHUP', group => 'CONN_AUTH_AUTH', short_desc => 'Lists libraries that may be called to validate OAuth v2 bearer tokens.', flags => 'GUC_LIST_INPUT | GUC_LIST_QUOTE | GUC_SUPERUSER_ONLY', diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c index a05fc356fc3..fc19e39e384 100644 --- a/src/backend/utils/misc/guc_tables.c +++ b/src/backend/utils/misc/guc_tables.c @@ -85,6 +85,7 @@ #include "storage/fd.h" #include "storage/io_worker.h" #include "storage/large_object.h" +#include "storage/numa_policy.h" #include "storage/pg_shmem.h" #include "storage/predicate.h" #include "storage/proc.h" diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample index b492b3af06c..e113742d96b 100644 --- a/src/backend/utils/misc/postgresql.conf.sample +++ b/src/backend/utils/misc/postgresql.conf.sample @@ -138,6 +138,8 @@ #huge_pages = try # on, off, or try # (change requires restart) #huge_page_size = 0 # zero for system default +#numa_nodes = '' # e.g. 0,1 or 0-3; empty applies no NUMA policy + # (change requires restart) # (change requires restart) #temp_buffers = 8MB # min 800kB #max_prepared_transactions = 0 # zero disables the feature diff --git a/src/include/storage/numa_policy.h b/src/include/storage/numa_policy.h new file mode 100644 index 00000000000..cf6d43984ce --- /dev/null +++ b/src/include/storage/numa_policy.h @@ -0,0 +1,24 @@ +/*------------------------------------------------------------------------- + * + * numa_policy.h + * Restrict the server to a set of NUMA nodes. + * + * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/storage/numa_policy.h + * + *------------------------------------------------------------------------- + */ +#ifndef NUMA_POLICY_H +#define NUMA_POLICY_H + +#include "utils/guc.h" + +/* GUC */ +extern PGDLLIMPORT char *numa_nodes; + +extern bool check_numa_nodes(char **newval, void **extra, GucSource source); +extern void NumaPolicyApplyCpuAffinity(void); + +#endif /* NUMA_POLICY_H */ diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index 5d81f5b13be..2864a4dfc24 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -24,6 +24,7 @@ tests += { 't/013_temp_obj_multisession.pl', 't/014_log_statement_max_length.pl', 't/015_temp_schema_exit_deferrable.pl', + 't/016_numa_nodes.pl', ], # The injection points are cluster-wide, so disable installcheck 'runningcheck': false, diff --git a/src/test/modules/test_misc/t/016_numa_nodes.pl b/src/test/modules/test_misc/t/016_numa_nodes.pl new file mode 100644 index 00000000000..030ac336b29 --- /dev/null +++ b/src/test/modules/test_misc/t/016_numa_nodes.pl @@ -0,0 +1,83 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Tests for the numa_nodes parameter: the default applies no policy, a value +# naming a node that cannot exist is refused at startup, and on a machine that +# has NUMA a valid node set is applied and reported. +# +# Only the third part needs NUMA hardware, and it is skipped when the server was +# not built with libnuma or when the machine reports no NUMA support, so the test +# is meaningful everywhere without requiring a particular topology. + +use strict; +use warnings FATAL => 'all'; + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('numa_nodes'); +$node->init; +$node->start; + +# The default must be empty, and must therefore apply no policy at all. +is($node->safe_psql('postgres', 'SHOW numa_nodes'), + '', 'numa_nodes is empty by default'); +is( $node->safe_psql( + 'postgres', + "SELECT context FROM pg_settings WHERE name = 'numa_nodes'"), + 'postmaster', + 'numa_nodes can only be set at server start'); + +$node->stop; + +# A node number that cannot exist must be refused before the server starts. +# This holds whether or not libnuma was compiled in; only the reason differs, +# so check that the right explanation is given in each case. +$node->append_conf('postgresql.conf', "numa_nodes = '999999'"); +ok(!$node->start(fail_ok => 1), + 'server refuses to start with a NUMA node that cannot exist'); + +my $log = slurp_file($node->logfile); +like( + $log, + qr/invalid value for parameter "numa_nodes"/, + 'the refusal names the parameter'); + +if (check_pg_config('#define USE_LIBNUMA 1')) +{ + like( + $log, + qr/must be a list of NUMA nodes/, + 'a libnuma build explains the expected syntax'); +} +else +{ + like( + $log, + qr/requires a server built with --with-libnuma/, + 'a build without libnuma explains the missing build option'); +} + +# With libnuma, and on a machine that actually reports NUMA support, a valid +# node set must be accepted, applied and visible. +SKIP: +{ + skip 'not built with libnuma', 2 + unless check_pg_config('#define USE_LIBNUMA 1'); + + $node->adjust_conf('postgresql.conf', 'numa_nodes', "'0'"); + + skip 'machine reports no NUMA support', 2 + unless $node->start(fail_ok => 1); + + is($node->safe_psql('postgres', 'SHOW numa_nodes'), + '0', 'numa_nodes is applied and reported'); + like( + slurp_file($node->logfile), + qr/server restricted to \d+ CPUs of NUMA nodes "0"/, + 'the server logs the restriction it applied'); + + $node->stop; +} + +done_testing();