In the PostgreSQL source code, you will find memory and compiler barriers in various places like pg_memory_barrier(), pg_write_barrier(), pg_read_barrier(), or pg_compiler_barrier(). These macros are needed to ensure that the compiler and CPU do not reorder memory accesses in a way that would break the correctness of the code. Closely related are volatile variables and atomic operations, which you will find in the source code as well.
PostgreSQL uses a process-based architecture, where a separate process handles each database connection. These processes use shared memory to communicate, allowing multiple processes to read and write values simultaneously. On multi-processor systems, these processes can run on different CPU cores, each with its own caches.
Intuitively, you would expect that if one process writes two values to shared memory, another process reading them would see the same order. But that’s not always the case, and it can cause tricky bugs that are hard to track down. To make matters worse, code that has run fine on x86 for years might suddenly break on ARM, a common platform for PostgreSQL, like AWS Graviton servers or Apple Silicon machines.
First, we’ll look at why compilers and CPUs reorder memory accesses (things like instruction scheduling, CPU pipelines, caches, store buffers, invalidate queues, and the memory models of x86 and ARM) and what barriers can prevent this. Then, we’ll go over PostgreSQL’s barrier macros with examples and explain how locks, atomic operations, and volatile fit in.
Running Example
Imagine the following code, which is executed by two different processes. These processes communicate through shared memory initialized to zeros. So, initially, shared->tuples is 0 and shared->done is false. The writer runs on CPU 1, and the reader runs on CPU 2.
typedef struct SharedState
{
int tuples; /* Initialized to 0 */
bool done; /* Initialized to false */
} SharedState;
/* Executed by CPU 1 */
void writer(SharedState *shared, int pages, int tuples_per_page)
{
shared->tuples = pages * tuples_per_page;
shared->done = true;
}
/* Executed by CPU 2 */
void reader(SharedState *shared)
{
while (!shared->done)
/* Wait for the writer to finish */;
Assert(shared->tuples != 0);
}
Looking at this code, you would expect that the reader always sees a value different from 0 in shared->tuples once shared->done is set to true (we assume that pages and tuples_per_page are always greater than zero). However, this is not guaranteed. The compiler and CPU can reorder the writes in the writer function, so that shared->done is set to true before shared->tuples is written. In this case, the reader can still see the initial value 0, and the assertion fails.
The reader can also reorder its reads so that it reads shared->tuples before shared->done. This can be caused by compiler optimizations or by CPU optimizations. To understand why this can happen, we need to look at how compilers and CPUs work.
Reordering of Memory Accesses
Software should run fast and utilize the underlying hardware as efficiently as possible. To achieve this, compilers and CPUs can reorder memory accesses to improve performance.
Pipelining in CPUs
Executing an instruction consists of several steps, which the CPU processes in separate stages. The textbook example is the classic RISC pipeline with five stages:
- Instruction fetch: The CPU reads the instruction from memory at the address stored in the program counter.
- Instruction decode: The CPU determines what the instruction should do (e.g., multiply two registers) and which registers are involved, and reads the values of these registers.
- Execute: The CPU operates, like multiplying values in the ALU or calculating a memory address.
- Memory access: Load instructions read data from memory, and store instructions write data to memory. In the rest of this article, we use the terms load and store for these memory reads and writes.
- Write back: The CPU writes the result into the destination register.
These stages form a pipeline, where each stage works on a different instruction at the same time. This allows multiple instructions to be processed simultaneously, improving overall performance. The following figure shows how four instructions are processed in the pipeline. Each instruction enters the pipeline one clock cycle after the previous one. In clock cycle 5 (highlighted), all four instructions are processed at the same time, each in a different stage.
Pipeline Depth and Width
Real-world CPUs have more stages and can process multiple instructions per clock cycle. The pipeline depth describes the number of stages an instruction passes through. Since each stage usually takes one clock cycle, the depth is often given in clock cycles. The pipeline width describes how many instructions can be processed in each stage per clock cycle.
For example, Intel’s Core microarchitecture (introduced in 2006 with the Core 2 CPUs) uses a 14-stage pipeline and can complete up to 4 instructions simultaneously (Intel IDF 2006). Arm specifies the pipeline depth of its Neoverse N2 server core as 10 clock cycles. The Arm Neoverse V2 core can decode 6 instructions and dispatch 8 micro-operations per clock cycle (Hot Chips 2023).
Instruction Scheduling and Out-of-Order Execution
A pipeline works at full speed only when instructions do not depend on each other. If one instruction needs the result of a previous one that is still being processed, it must wait, stalling the pipeline. In our writer() function, for example, the store to tuples has to wait for the result of the multiplication, while the store to done does not depend on it. To prevent these stalls, the compiler rearranges instructions so that independent ones run while the CPU waits for a result. This process is known as instruction scheduling. Modern CPUs go one step further and reorder instructions themselves at runtime (out-of-order execution). How the CPU can reorder memory accesses is discussed in the section about CPU reordering.
However, both the compiler and the CPU are only required to preserve the order of instructions that depend on each other within the same thread. Whether another CPU core observes the memory accesses in a different order is not taken into account.
Compiler Reordering
The C standard explicitly allows the compiler to transform code, as long as a single thread cannot tell the difference:
“[…] data-race-free programs cannot observe most program transformations that do not change single-threaded program semantics. In fact, most single-threaded program transformations continue to be allowed, since any program that behaves differently as a result must contain undefined behavior.”
— C11 standard, §5.1.2.4 (NOTE 12), N1570 draft
In other words, the compiler treats the code as if only one thread is running. As long as that thread’s outcome doesn’t change, the compiler can reorder, combine, or remove memory accesses. Only programs that use shared memory without proper synchronization (i.e., that contain a data race) can detect these changes, and the C standard says such programs have undefined behavior.
Our example accesses done and tuples from two processes without synchronization, which is similar to different threads accessing the same memory. So the compiler is free to reorder or even eliminate these accesses.
Example: Reordered Stores
To illustrate the reordering, let’s compile the writer() function from our example with optimization level -O2 and look at the generated assembly code. The full source code can be found here. Note that tuples is computed from two parameters. If tuples were a constant or a plain parameter, both stores could be executed immediately, and the compiler would have no reason to reorder them.
The code is compiled with GCC 14.2 on x86-64 and disassembled with objdump:
$ gcc -O2 -c compiler_reordering.c -o compiler_reordering.o
$ objdump -d --no-show-raw-insn compiler_reordering.o
The disassembled writer() function looks as follows:
0000000000000000 <writer>:
0: imul %edx,%esi # pages * tuples_per_page
3: movb $0x1,0x4(%rdi) # done = true
7: mov %esi,(%rdi) # tuples = pages * tuples_per_page
9: ret
Note: On x86-64 Linux, the first three function parameters are passed in the registers rdi (shared), rsi (pages), and rdx (tuples_per_page). Since pages and tuples_per_page are 32-bit integers, the code uses the lower 32 bits of these registers, which are called esi and edx. The notation 0x4(%rdi) means the memory at the address stored in rdi plus 4 bytes. Since tuples is a 4-byte integer at the beginning of the struct, (%rdi) refers to shared->tuples and 0x4(%rdi) to shared->done.
The compiler has swapped the two stores. done is set to true (offset 3) before tuples is written (offset 7). The store of done does not depend on the result of the multiplication, so that the compiler can schedule it before the store of tuples. For a single thread, the result is the same. However, a reader running on another CPU can see done == true while tuples still contains the old value.
The compiler also optimizes the reader, in an even more surprising way. We will look at this in the section about volatile.
Compiler Barrier
To make the example work, we need to ensure the compiler does not reorder the two stores. We can achieve this with a compiler barrier.
Compiler barrier: Prevents only the compiler from moving memory accesses across it. It does not emit any CPU instruction.
In plain C11, we can use atomic_thread_fence() to establish a memory barrier (a barrier that also restricts the CPU, which is discussed in the next section). This function is defined in <stdatomic.h> and takes a memory order as an argument. The memory order specifies how the compiler and CPU should treat memory accesses across the barrier.
PostgreSQL does not use the C11 functions from <stdatomic.h> directly. Its barrier and atomics infrastructure is older than the C11 support of the compilers PostgreSQL targets (PostgreSQL required only C99 until version 18; PostgreSQL 19 raised the requirement to C11), and even in C11, atomics are an optional feature (__STDC_NO_ATOMICS__). Instead, PostgreSQL provides its own barrier macros, which are implemented with compiler builtins such as __atomic_thread_fence() (the same mechanism that is used for the C11 fences) or with architecture-specific code.
A compiler barrier in PostgreSQL can be established using the pg_compiler_barrier() macro. This is defined as follows:
#define pg_compiler_barrier() __asm__ __volatile__("" ::: "memory")
This macro uses an inline assembly statement with an empty string, so it doesn’t generate any CPU instructions. The __volatile__ keyword makes sure the compiler doesn’t remove the statement. The “memory” clobber tells the compiler that the statement might read or change any memory. As a result, the compiler must complete all memory accesses before the statement and can’t move memory operations past it.
When we modify the writer() function to include a compiler barrier between the two stores, the compiler will not reorder them:
void writer(SharedState *shared, int pages, int tuples_per_page)
{
shared->tuples = pages * tuples_per_page;
pg_compiler_barrier();
shared->done = true;
}
The full source code can be found here. And the disassembled code now looks like this:
0000000000000000 <writer>:
0: imul %edx,%esi # pages * tuples_per_page
3: mov %esi,(%rdi) # tuples = pages * tuples_per_page
5: movb $0x1,0x4(%rdi) # done = true
9: ret
The store operations are performed in the same order as in the C code: at offset 3 the new value of tuples is written, and at offset 5 done is set to true.
However, a compiler barrier only restricts the compiler. The CPU can still reorder the memory accesses at runtime, which we look at in the next section. So, the macro is rarely used directly and serves mostly as a building block for the other barrier macros in PostgreSQL.
CPU Reordering and Cache Coherency
The CPU can also reorder memory accesses. Each CPU architecture has its own rules for how it can reorder memory accesses. One reason for memory reordering is that modern CPUs have multiple cores, each with its own cache.
Since each CPU core operates independently, it can read and write values in its own cache without immediately updating the main memory. This can lead to situations where one core sees a different value than another core for the same memory location. To ensure that all cores see a consistent view of memory, CPUs implement cache coherency protocols. The cores, their caches, and the main memory are connected by an interconnect (historically a shared bus, today often a ring or mesh network), which is used to transfer cache lines and to exchange the messages of the cache coherency protocol.
MESI Protocol
The basis of most cache coherency protocols is the MESI protocol, which stands for Modified, Exclusive, Shared, and Invalid. This protocol ensures that when one core modifies a value in its cache, other cores are notified and must invalidate their copies. Real CPUs use extended variants, like MESIF on Intel CPUs, which adds a Forward state, or MOESI on AMD CPUs, which adds an Owned state (AMD64 Architecture Programmer’s Manual, Volume 2, Section 7.3).
Each cache line (a small block of memory, typically 64 bytes) can be in one of four states:
- Modified: The cache line has been modified by the core and is different from main memory. The core must write the value back to main memory before another core can read it.
- Exclusive: The cache line is only in this core’s cache and is the same as main memory.
- Shared: The cache line is in multiple cores’ caches and is the same as main memory.
- Invalid: The cache line is not valid in this core’s cache.
For example, if one core writes to a cache line in the shared state, it must first invalidate copies in other cores’ caches. Therefore, the CPU sends an invalidation message to other cores, which then mark their copies of that cache line as invalid. After all other cores have acknowledged the invalidation, the writing core can change the state of the cache line to modified and write the new value. If two cores want to modify the same cache line at the same time, the requests are serialized, so all cores observe the stores to a cache line in the same order. If both cores write to the same address, the store serialized last wins; which one wins depends on the hardware and is not predictable by the program.
The MESI protocol keeps caches coherent and does not reorder memory accesses. But waiting for all other cores to acknowledge an invalidation can be slow. To speed things up, CPUs use optimizations like store buffers and invalidate queues, which can reorder memory accesses.
To prevent the CPU from reordering memory accesses, we can use a memory barrier:
(Full) memory barrier: Prevents the compiler and the CPU from moving any loads and stores across it, so it always includes a compiler barrier.
Store Buffers
To speed up stores that have to wait for the invalidation, CPUs often have a store buffer that holds the new value until it can be written to the cache line. This allows the CPU to continue executing instructions without waiting for the store to complete. So, the CPU performs stores in two ways:
- When the CPU writes to a cache line that is in the modified or exclusive state, it can write directly to the cache line.
- When the CPU writes to a cache line that is in the shared or invalid state, it must first invalidate the copies in other cores’ caches (and fetch the cache line if it is not cached). The new value is then kept in the store buffer until it can be written to the cache line.
To make sure a CPU can see its own stores, the CPU checks its store buffer on every load (store forwarding). So, if a core writes a value to a cache line and then reads it back, it will see the new value even if it has not yet been written to the cache line.
Write reordering: Since the first path updates the cache line directly, it is faster than the second path, which requires invalidation and waiting for the store buffer to be flushed. So, if an instruction A comes first in the program but has to go into the store buffer, and a later instruction B can write directly to the cache line, the change from instruction B is visible to other cores before the change from instruction A.
This example assumes that both values are located in different cache lines; otherwise, both stores would take the same path. Furthermore, this depends heavily on the CPU architecture. This reordering does not happen on x86: there, the store buffer is processed in FIFO order, so a later store cannot overtake an earlier store that is still waiting in the store buffer. However, it can happen on CPUs with a weaker memory model, such as ARM.
Write memory barrier: Ensures that all stores before the barrier are visible to other cores before any stores after the barrier. It also includes a compiler barrier.
Invalidate Queues
When an invalidation message arrives from another core, the CPU must invalidate the cache line in its own cache. This is usually done in the background, while the CPU continues executing instructions. To do this, the CPU uses an invalidate queue that holds invalidation messages until it can process them.
Read reordering: The CPU acknowledges the invalidation message when it is added to the invalidate queue, not when it is processed and the cache line is actually invalidated. Until then, the CPU can still read the old value from its cache. So, even if the writer makes sure tuples is written before done, the reader can still see the old value of tuples after it has seen the new value of done.
Read memory barrier: Ensures that all loads before the barrier are completed before any loads after the barrier. It also includes a compiler barrier.
Memory Models of x86 and ARM
As mentioned before, a CPU architecture’s memory model defines the rules for how memory accesses can be reordered. The x86 architecture has a strong memory model that allows only a few reorderings, while ARM has a weaker memory model that allows more reorderings. ARM describes its memory model as follows:
“Armv8-A implements a weakly-ordered memory architecture. This architecture permits memory accesses which impose no dependencies to be issued or observed, and to complete in a different order from the order that is specified by the program order.”
— Arm, Learn the architecture - Memory Systems, Ordering, and Barriers, Memory ordering
| Reordering | Meaning | Allowed on x86 | Allowed on ARM |
|---|---|---|---|
| Store→Store | A later store becomes visible before an earlier store | No | Yes |
| Load→Load | A later load reads older data than an earlier load | No | Yes |
| Load→Store | A later store becomes visible before an earlier load has completed | No | Yes |
| Store→Load | A later load completes before an earlier store is visible | Yes | Yes |
Sources: x86: Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A, Section 11.2.2 “Memory Ordering in P6 and More Recent Processor Families”; ARM: Learn the architecture - Memory Systems, Ordering, and Barriers, “Memory ordering”.
The only reordering that x86 allows (Store→Load) is due to the store buffer. A Store→Load reordering can occur when a store is still in the store buffer, and a subsequent load from a different address can be served from the cache. As other cores can’t see the store buffer, the load will be served prior to the store becoming visible to them. Store forwarding doesn’t stop this, as it only applies to loads from the same address.
For our example, using the x86 architecture, the CPU will reorder neither the two stores in writer() nor the two loads in reader(). Only the compiler can break the example, so compiler barriers are sufficient. On ARM, the CPU can reorder both, so the writer requires a write memory barrier and the reader a read memory barrier.
Note: A full memory barrier is different from combining a read and a write memory barrier. A full memory barrier ensures that all loads and stores before the barrier are completed before any loads and stores after the barrier. The individual read and write memory barriers guarantee Load→Load and Store→Store ordering, but neither Store→Load nor Load→Store ordering.
Example: Store→Load
The Intel manual (Volume 3A, Example 11-3) contains a simple example that illustrates the Store→Load reordering, called the store buffering litmus test (a litmus test is a minimal program that checks whether a CPU allows a specific reordering). In this example, two processes first write their own variable and then read the other process’s variable. x and y are located in shared memory and are initially 0:
/* Executed by CPU 1 */ /* Executed by CPU 2 */
x = 1; y = 1;
r1 = y; r2 = x;
At first glance, you might expect that at least one of the two processes would read the value 1. The CPU that loads last should see the other CPU’s store. But because of Store→Load reordering, it is possible for both r1 = 0 and r2 = 0 to occur, even on x86 systems. In this case, each store sits in its CPU’s store buffer, and each load gets its value from the cache before the store is visible to the other CPU. As a result, both CPUs read the old value 0. Intel’s manual explicitly allows this reordering:
“The Intel-64 memory-ordering model allows a load to be reordered with an earlier store to a different location. However, loads are not reordered with stores to the same location.”
— Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A, Section 11.2.3.4, Intel
A compiler barrier does not help here because the reordering happens inside the CPU. Read and write memory barriers are not enough either. A write barrier only orders stores with respect to later stores, and a read barrier only orders loads with respect to other loads. Only a full memory barrier placed between the store and the load ensures that the store has left the store buffer and is visible to other cores before the load happens. The earlier statement that compiler barriers are enough on x86 applies only to our example, which needs just Store→Store and Load→Load ordering. PostgreSQL uses this pattern, with a full memory barrier, for latches, which we will discuss later.
Example: Load→Store
The example for Load→Store reordering is the mirror image: each process first reads the other process’s variable, then writes to its own. This example comes from the Intel manual (Volume 3A, Example 11-2) and is called the load buffering litmus test. As before, x and y are in shared memory, and both start at 0:
/* Executed by CPU 1 */ /* Executed by CPU 2 */
r1 = x; r2 = y;
y = 1; x = 1;
In this case, getting r1 = 1 and r2 = 1 seems impossible because each process reads before it writes. On x86, this outcome is prevented. On ARM, though, it can happen. For instance, if the load misses the cache and has to wait for the cache line, but the cache line for the later store is already exclusive, the store might become visible to the other CPU before the load gets its value. To avoid this, you need a full memory barrier between the load and the store.
Memory Ordering in PostgreSQL
After we have looked at the reasons for reordering and how to prevent it, we can now look at how PostgreSQL implements this and uses it.
Barrier Macros
The following table summarizes the causes of reordering discussed so far and the barrier that is needed to prevent them. Each memory barrier also includes a compiler barrier.
| Cause | Reordering | Needed barrier | PostgreSQL macro |
|---|---|---|---|
| Compiler (instruction scheduling) | Any independent memory accesses | Compiler barrier | pg_compiler_barrier() |
| Store buffer | Store→Store (not on x86) | Write memory barrier | pg_write_barrier() |
| Invalidate queue | Load→Load (not on x86) | Read memory barrier | pg_read_barrier() |
| Load waits for a cache line, later store is written directly | Load→Store (not on x86) | Full memory barrier | pg_memory_barrier() |
| Store buffer, load is served from the cache | Store→Load (also on x86) | Full memory barrier | pg_memory_barrier() |
How these macros work depends on the CPU architecture’s memory model. On x86, read and write barriers are just compiler barriers because x86 does not reorder Load→Load or Store→Store operations (arch-x86.h). Only the full memory barrier actually triggers a CPU instruction. On ARM, PostgreSQL uses the compiler’s built-in __atomic_thread_fence() (generic-gcc.h), which issues a dmb (data memory barrier) instruction for all three types of memory barriers.
| Macro | x86 | ARM (AArch64) |
|---|---|---|
pg_compiler_barrier() |
Compiler barrier only | Compiler barrier only |
pg_write_barrier() |
Compiler barrier only | __atomic_thread_fence(__ATOMIC_RELEASE) → dmb ish |
pg_read_barrier() |
Compiler barrier only | __atomic_thread_fence(__ATOMIC_ACQUIRE) → dmb ishld |
pg_memory_barrier() |
lock; addl $0,0(%rsp) |
__atomic_thread_fence(__ATOMIC_SEQ_CST) → dmb ish |
ish (inner shareable) means the barrier affects all CPU cores in the system and orders both loads and stores. ishld only orders earlier loads with later loads and stores, which is enough for a read barrier (Arm documentation).
The full memory barrier on x86 uses the lock prefix on an instruction that adds 0 to the top of the stack, which does not change any data, so nothing needs to be undone. According to a comment in the source code, ““lock; addl” has worked for longer than “mfence”. It’s also rumored to be faster in many scenarios.” The README.barrier file summarizes the effect of the weaker barriers:
“On machines with strong memory ordering, these weaker barriers will simply prevent compiler rearrangement, without emitting any actual machine code. On machines with weak memory ordering, they will prevent compiler reordering and also emit whatever hardware barrier may be required.”
— PostgreSQL source code, src/backend/storage/lmgr/README.barrier
Barrier Pairing
A barrier only affects the memory accesses of the process that runs it. That’s why barriers are usually used in pairs: a write barrier for the writer and a matching read barrier for the reader. With both barriers in place, our example works correctly:
/* Executed by CPU 1 */
void writer(SharedState *shared, int pages, int tuples_per_page)
{
shared->tuples = pages * tuples_per_page;
pg_write_barrier();
shared->done = true;
}
/* Executed by CPU 2 */
void reader(SharedState *shared)
{
bool done;
do
{
done = shared->done;
pg_read_barrier(); /* pairs with pg_write_barrier() in writer() */
} while (!done);
Assert(shared->tuples != 0);
}
The write barrier ensures that the new value of tuples is visible before done is set to true. But that alone is not enough. If there is no read barrier, the reader might still load tuples before done because of things like an invalidate queue on its CPU, and end up seeing the old value. The read barrier guarantees that tuples is only loaded after done has been read as true. The opposite is also important: a read barrier in the reader does not help if the writer’s stores are seen in the wrong order.
The read barrier goes inside the loop, right after loading done, so that the last time done is loaded (when it returns true), there is always a barrier before reading tuples. With a plain while (!shared->done) loop, the last load would exit the loop before the barrier is executed.
On x86, both barriers are only compiler barriers, which matches our earlier observation that compiler barriers are enough for this example on x86. On ARM, they emit dmb instructions. PostgreSQL often documents such pairs in the source code. For example, a read barrier in procarray.c is marked with the comment “pairs with barrier in GetNewTransactionId()”. We will look at this example in the next section.
Examples
Let’s look at two places in the PostgreSQL source code that use barriers: GetNewTransactionId() uses a pair of write and read barriers, like our running example, and SetLatch() needs a full memory barrier because of Store→Load reordering.
GetNewTransactionId(): Write and Read Barriers
When a transaction starts a subtransaction, such as with a SAVEPOINT, and the subtransaction receives a transaction ID (XID), GetNewTransactionId() saves this XID in a small array in shared memory. Other processes check this array to see if a transaction is still running. The function first adds the new XID to the array and then increases the entry count:
MyProc->subxids.xids[nxids] = xid;
pg_write_barrier();
MyProc->subxidStatus.count = substat->count = nxids + 1;
This is the same pattern as in our running example: first the data is written (the XID instead of tuples), then it is published (the counter instead of done). The comment in the source code describes what could go wrong without the barrier:
“Use of a write barrier prevents dangerous code rearrangement in this function; other backends could otherwise e.g. be examining my subxids info concurrently, and we don’t want them to see an invalid intermediate state, such as an incremented nxids before the array entry is filled.”
— PostgreSQL source code, src/backend/access/transam/varsup.c
The matching read barrier can be found in TransactionIdIsInProgress(). The reader first loads the counter and only then reads the array entries:
pxids = other_subxidstates[pgxactoff].count;
pg_read_barrier(); /* pairs with barrier in GetNewTransactionId() */
pgprocno = arrayP->pgprocnos[pgxactoff];
proc = &allProcs[pgprocno];
for (j = pxids - 1; j >= 0; j--)
{
/* Fetch xid just once - see GetNewTransactionId */
TransactionId cxid = UINT32_ACCESS_ONCE(proc->subxids.xids[j]);
[...]
}
The two barriers work together to ensure that every entry visible to the reader, based on the counter, has already been written. Because only Store→Store and Load→Load ordering is required, read and write barriers are enough. On x86, these barriers require no extra CPU instructions.
The macro UINT32_ACCESS_ONCE() used in the loop is defined in procarray.c as ((uint32)(*((volatile uint32 *)&(var)))). This macro accesses the array entry using a volatile pointer, which makes the compiler load the value only once. If you do not use it, the compiler might load xids[j] again later instead of keeping it in a register. Because another process could change the entry in the meantime, the two loads might return different values. We will discuss volatile in more detail later.
SetLatch(): Full Memory Barrier
A latch lets a PostgreSQL process sleep until another process wakes it up, such as when new work arrives. The Latch structure has two flags in shared memory. The is_set flag shows if the latch is set, and maybe_sleeping shows if the latch owner might be sleeping and needs to be woken up. To avoid unnecessary wakeups, the process setting the latch signals the owner only if maybe_sleeping is set. SetLatch() does the following:
latch->is_set = true;
pg_memory_barrier();
if (!latch->maybe_sleeping)
return;
/* ... wake up the owner of the latch ... */
On the other side, the owner of the latch sets maybe_sleeping before going to sleep in WaitEventSetWait() and checks again whether the latch has been set in the meantime:
if (set->latch && !set->latch->is_set)
{
/* about to sleep on a latch */
set->latch->maybe_sleeping = true;
pg_memory_barrier();
/* and recheck */
}
if (set->latch && set->latch->is_set)
{
/* ... the latch is set, don't sleep ... */
}
Each side first stores its own flag, then loads the other side’s flag. This matches the store buffering litmus test from the Store→Load reordering section. Without barriers, both stores might still be in the store buffers when the loads happen. In that case, SetLatch() would see maybe_sleeping == false and not wake the owner, while the owner would see is_set == false and go to sleep. The wakeup would be missed, and the owner would sleep until a timeout or another event.
Because this is a Store→Load reordering, it can also occur on x86, so both sides need a full memory barrier. Read and write barriers alone are not enough. With full barriers, at least one side will see the other’s store: either SetLatch() sees maybe_sleeping == true and wakes the owner, or the owner sees is_set == true and stays awake.
Locks
Locks can also prevent memory ordering bugs in PostgreSQL.
“The simplest (and often best) way to avoid memory ordering bugs is to protect the data structures involved with an lwlock.”
— PostgreSQL source code, src/backend/storage/lmgr/README.barrier
PostgreSQL uses spinlocks for small critical sections that only need a few instructions. A spinlock uses the type slock_t, is set up with SpinLockInit(), and you use SpinLockAcquire() and SpinLockRelease() to lock and unlock it (spin.h). How spinlocks are implemented and how they can be monitored is described in my article about spinlocks. For example, you can fix our example by protecting both variables with a spinlock:
typedef struct SharedState
{
slock_t mutex; /* Initialized with SpinLockInit() */
int tuples; /* Initialized to 0 */
bool done; /* Initialized to false */
} SharedState;
/* Executed by CPU 1 */
void writer(SharedState *shared, int pages, int tuples_per_page)
{
SpinLockAcquire(&shared->mutex);
shared->tuples = pages * tuples_per_page;
shared->done = true;
SpinLockRelease(&shared->mutex);
}
/* Executed by CPU 2 */
void reader(SharedState *shared)
{
bool done = false;
int tuples = 0;
while (!done)
{
SpinLockAcquire(&shared->mutex);
done = shared->done;
tuples = shared->tuples;
SpinLockRelease(&shared->mutex);
}
Assert(tuples != 0);
}
The reader can no longer see done == true without the new value of tuples, because the writer changes both variables while holding the lock. So, the reader sees either the old values of both variables or the new values of both. No explicit barriers are needed, neither on x86 nor on ARM. Note that the reader repeatedly acquires the spinlock in a tight loop only to keep the example simple. Real PostgreSQL code would wait for such an event on a latch or a condition variable instead.
However, a lock is not a full memory barrier. It only prevents memory accesses from moving out of the critical section (the code between acquiring and releasing the lock; not to be confused with PostgreSQL’s START_CRIT_SECTION(), which is a different mechanism). For spinlocks, this is defined in s_lock.h:
“TAS() and TAS_SPIN() must guarantee that loads and stores issued after the macro are not executed until the lock has been obtained. Conversely, S_UNLOCK() must guarantee that loads and stores issued before the macro have been executed before the lock is released.”
— PostgreSQL source code, src/include/storage/s_lock.h
TAS() (test-and-set) is an atomic instruction that acquires the spinlock, and S_UNLOCK() releases it. Acquiring the lock uses acquire semantics. This means memory accesses that happen after the lock is acquired cannot be moved before it. Releasing the lock uses release semantics, so memory accesses before the lock is released cannot be moved after it.
Still, memory accesses before the acquire can move into the critical section, and accesses after the release can also move into it. This is fine because the lock only protects data used inside the critical section. C11 uses the same terms: memory_order_acquire and memory_order_release give these one-way guarantees.
How these guarantees work depends on the CPU architecture’s memory model. On x86, TAS() uses the lock xchgb instruction (s_lock.h). The lock prefix, like in lock addl used by pg_memory_barrier(), acts as a full barrier.
Releasing the spinlock is even simpler: S_UNLOCK() is just a compiler barrier, then a plain store of 0 into the lock variable. No CPU barrier is needed because x86 does not reorder Load→Store or Store→Store operations (see the table above). This means all loads and stores in the critical section finish before the lock is released. The source code makes this clear:
“Note that this implementation is unsafe for any platform that can reorder a memory access (either load or store) after a following store. That happens not to be possible on x86 and most legacy architectures (some are single-processor!), but many modern systems have weaker memory ordering.”
— PostgreSQL source code, src/include/storage/s_lock.h
On ARM, PostgreSQL uses the compiler builtins __sync_lock_test_and_set() and __sync_lock_release() (s_lock.h). According to the GCC manual, the first one is “not a full barrier, but rather an acquire barrier” and the second one is “not a full barrier, but rather a release barrier”, which is exactly what a spinlock needs.
LWLocks (lightweight locks, which support shared and exclusive modes and let waiting processes sleep instead of spin) provide even stronger guarantees. They are built on atomic operations with full barrier semantics: acquiring an LWLock uses pg_atomic_compare_exchange_u32(), which, according to a comment in lwlock.c, “doubles as a memory barrier”, and releasing it uses pg_atomic_sub_fetch_u32().
History of Spinlocks and Barriers
Before PostgreSQL supported memory barriers, spinlocks were sometimes used just for their ordering guarantees. In 2008, a rewrite of the shared invalidation message queue (sinvaladt.c) introduced a memory ordering bug (fad153ec452). In this setup, a writer adds a message to an array and then increments maxMsgNum, while readers check maxMsgNum to see how many messages are available. This matches the pattern in our example. The rewrite assumed that maxMsgNum could be read and written without a lock, as Tom Lane wrote on the mailing list:
“[…] we are already assuming in several places that reading or writing an int is atomic, and if we assume that here too, it seems to work fine.”
— Tom Lane, pgsql-patches, 2008-06-19
The assumption about atomicity was correct, but it ignored the ordering: a reader could see the incremented maxMsgNum before the message itself. Tom Lane fixed the bug by protecting maxMsgNum with a spinlock and explained this in the commit message:
“The value itself is atomic, sure, but on processors with weak memory ordering a reader can see the value change before it sees the associated message written into the buffer array. Fix by introducing a spinlock that’s used just to read and write maxMsgNum. (We could do this with less overhead if we recognized a concept of “memory access barrier”; is it worth introducing such a thing? At the moment probably not — I can’t measure any clear slowdown from adding the spinlock, so this solution is probably fine.)”
— Tom Lane, commit dab421d2f0c
Memory barriers were added in PostgreSQL 9.2 (0c8eda62588). Until PostgreSQL 9.5, spinlocks only prevented the CPU from reordering memory accesses, but not the compiler. Therefore, all data protected by a spinlock had to be accessed through volatile pointers. This changed in PostgreSQL 9.5, when the spinlock functions also became compiler barriers. Robert Haas wrote in the commit message:
“Previously, they functioned as barriers against CPU reordering but not compiler reordering, an odd API that required extensive use of volatile everywhere that spinlocks are used. That’s error-prone and hurts performance, so change it.”
— Robert Haas, commit 0709b7ee72e
The spinlock for maxMsgNum remained until 2026 (PostgreSQL 20), when maxMsgNum became an atomic variable accessed with pg_atomic_read_membarrier_u32() and pg_atomic_write_membarrier_u32(). The commit message for df3978c2340 says: “The spinlock exists only to provide memory barriers, so by converting the variable to an atomic and using the barrier-providing accessors in the spinlock’s place, we can remove the spinlock.”
Atomic Operations
The last step in this history already used atomic operations, which we cover in this section.
Reading or writing a value in a regular operation is not necessarily atomic. If a process reads a value while another process is writing it, the reading process can see an intermediate state. For example, if a 32-bit integer is written in two 16-bit steps, the reader can see the first half of the new value and the second half of the old value. This can lead to unexpected behavior. Atomic operations ensure that a read, write, or modification happens in a single step, so that no other process can see an intermediate state.
On platforms that PostgreSQL supports, aligned 32-bit reads and writes happen in a single step. A more important case is a read-modify-write operation like counter++. This involves loading a value, adding to it, and storing it again. If two processes do this at the same time, they might both load the same old value, so one increment can be lost. Atomic read-modify-write operations make sure all steps happen as a single, indivisible action.
Atomic Operations in PostgreSQL
In C11, atomic operations are defined in <stdatomic.h>. PostgreSQL does not use these functions directly for the same reason as with barriers (see the section about compiler barriers). PostgreSQL added its atomics API in 9.5 (2014), and it still provides its own atomic operations.
The following table shows the most important atomic operations provided by PostgreSQL:
| Operation | PostgreSQL function | Barrier semantics | C11 equivalent |
|---|---|---|---|
| Load | pg_atomic_read_u32() |
None | atomic_load_explicit(..., memory_order_relaxed) |
| Store | pg_atomic_write_u32() |
None | atomic_store_explicit(..., memory_order_relaxed) |
| Load with barrier | pg_atomic_read_membarrier_u32() |
Full | atomic_load() |
| Store with barrier | pg_atomic_write_membarrier_u32() |
Full | atomic_store() |
| Exchange | pg_atomic_exchange_u32() |
Full | atomic_exchange() |
| Compare and swap | pg_atomic_compare_exchange_u32() |
Full | atomic_compare_exchange_strong() |
| Fetch and add / sub / and / or | pg_atomic_fetch_add_u32(), pg_atomic_fetch_sub_u32(), pg_atomic_fetch_and_u32(), pg_atomic_fetch_or_u32() |
Full | atomic_fetch_add(), atomic_fetch_sub(), atomic_fetch_and(), atomic_fetch_or() |
Source: src/include/port/atomics.h. The C11 functions without the _explicit suffix use memory_order_seq_cst, which roughly corresponds to PostgreSQL’s full barrier semantics. Full barrier semantics means that the atomic operation itself acts as a memory barrier in both directions: no memory access before it can be moved after it, and no memory access after it can be moved before it.
64-bit Atomic Operations
All operations in the table are also available in a 64-bit version, which uses the type pg_atomic_uint64 instead of pg_atomic_uint32 (for example, pg_atomic_read_u64()). The 64-bit versions work the same way, but on 32-bit platforms, a 64-bit value might be read or written in two 32-bit steps, so the intermediate state described earlier can actually happen. On platforms that guarantee atomic, aligned 64-bit accesses, such as x86-64 and AArch64, pg_atomic_read_u64() and pg_atomic_write_u64() are just regular memory accesses. On other platforms, PostgreSQL handles the read with a compare-and-swap and the write with an atomic exchange, both of which access the value in a single step (generic.h). If a platform does not support 64-bit atomic operations at all, PostgreSQL simulates them by protecting the value with a spinlock (fallback.h), which, according to the source code, is “slower than native atomics support, but not unusably slow”.
Note: Atomicity and ordering are separate guarantees. An atomic operation makes sure that no other process sees an intermediate state of this variable. However, it does not control the order of accesses to other variables. The functions pg_atomic_read_u32() and pg_atomic_write_u32() do not include barrier semantics, so both the compiler and CPU may reorder them with other memory accesses, just like the plain accesses in our running example. If you need to control the order, you still need a barrier or an operation that provides full barrier semantics.
Example: Parallel Sort
A good example of atomic operations in PostgreSQL is the parallel sort in tuplesort.c. Here, the leader process and worker processes use two shared memory counters: currentWorker, which gives each worker a unique number, and workersFinished, which tracks how many workers have finished sorting. Previously, both counters were regular int variables protected by a spinlock. The commit ee97eef695e changed them to atomic variables and removed the spinlock.
Before the workers are started, the leader initializes both counters:
pg_atomic_init_u32(&shared->currentWorker, 0);
pg_atomic_init_u32(&shared->workersFinished, 0);
Each worker gets its number by incrementing currentWorker. Before the commit, this was a counter++ protected by the spinlock:
SpinLockAcquire(&shared->mutex);
worker = shared->currentWorker++;
SpinLockRelease(&shared->mutex);
Without a spinlock, two workers might load the same value and end up with the same number. This is the lost update problem shown in the figure above. With pg_atomic_fetch_add_u32(), the old value is loaded and the counter is incremented as a single, indivisible step. This way, each worker gets a unique number without needing a spinlock.
return pg_atomic_fetch_add_u32(&state->shared->currentWorker, 1);
When a worker has finished, it stores the metadata of its result in its own slot of the tapes array and increments workersFinished:
shared->tapes[state->worker] = output;
pg_atomic_fetch_add_u32(&shared->workersFinished, 1);
This follows the same pattern as our running example. First, the data is written (using tapes instead of tuples), and then completion is signaled (with workersFinished instead of done). Earlier, the spinlock also controlled the order of these two actions. Now, without the spinlock, the full barrier semantics of pg_atomic_fetch_add_u32() ensure that the store to tapes happens before the counter is incremented. The commit message explains it like this:
“Note that the spinlock also covered the write of each worker’s tape metadata. Removing it is still okay: each worker writes only its own slot, and the atomic increment that follows is a full barrier. Furthermore, the leader doesn’t read the slot values until all workers have finished.”
— Nathan Bossart, commit ee97eef695e
On the other side, the leader reads the counter with pg_atomic_read_membarrier_u32(), which also has full barrier semantics, before it reads the tapes array:
workersFinished = pg_atomic_read_membarrier_u32(&shared->workersFinished);
if (nParticipants != workersFinished)
elog(ERROR, "cannot take over tapes before all workers finish");
Volatile
The volatile qualifier is often discussed along with memory barriers, but it addresses a different issue. It only limits how the compiler accesses a variable. In this section, we explain what volatile does, why it cannot replace memory barriers, and where PostgreSQL still uses it.
Volatile in Our Running Example
There is one more problem in the reader of our running example that we haven’t discussed yet: the compiler also optimizes the reader. Because it assumes only one thread is running and the loop body doesn’t change shared->done, it treats the value as constant during the loop. As a result, it reads done just once. If you compile the reader() function from compiler_reordering.c using the same commands as before, you’ll get the following assembler code:
0000000000000010 <reader>:
10: cmpb $0x0,0x4(%rdi) # done == false?
14: je 21 <reader+0x11> # if so, jump to offset 21
16: mov (%rdi),%edx # load tuples
18: test %edx,%edx # tuples == 0?
1a: je 20 <reader+0x10> # if so, jump to the assertion failure (target set by the linker)
20: ret
21: jmp 21 <reader+0x11> # endless loop, done is never read again
If done is false when the function is called, the code jumps to offset 21, which is a jump to itself. The value of done is never read again, so the reader waits forever, even after the writer has set done to true.
Note: The jump at offset 1a looks like it jumps to the ret instruction at offset 20. But the code for the failed assertion is in a different section of the object file, and its address isn’t known until linking. Because of this, the compiler (more precisely, the assembler) sets the jump offset to 0, which points to the next instruction, and records a relocation entry. When the program is linked, the linker updates the offset with the actual address of the assertion code.
To force the compiler to read done in every iteration, the reader can access the shared state through a volatile pointer:
void reader(volatile SharedState *shared)
{
while (!shared->done)
/* Wait for the writer to finish */;
Assert(shared->tuples != 0);
}
The volatile qualifier lets the compiler know that a value might change outside the program’s control. This means each time the code accesses that value, it must actually read from memory, and the compiler can’t skip or combine these accesses. You can find the full source code here. In this example, done is loaded during every loop iteration (offsets 10 to 16):
0000000000000010 <reader>:
10: movzbl 0x4(%rdi),%eax # load done
14: test %al,%al # done == false?
16: je 10 <reader> # if so, load done again
18: mov (%rdi),%eax # load tuples
1a: test %eax,%eax # tuples == 0?
1c: je 22 <reader+0x12> # if so, jump to the assertion failure (target set by the linker)
22: ret
Such a change outside the program’s control can come from another process that has access to the variables via shared memory or, for example, from memory regions that are mapped by I/O devices (e.g., a status register of a hardware component). However, volatile is not a replacement for memory barriers; the CPU can still reorder the memory accesses. Furthermore, the compiler can still reorder volatile accesses with non-volatile accesses.
A compiler barrier in the loop (see compiler_barrier.c) would also solve the reader problem, since the compiler must assume the barrier can modify any memory and must reload done after it. The same applies to the spinlock version of our example in the section about locks, because the spinlock functions also act as compiler barriers (spin.h).
Besides shared memory, PostgreSQL also uses volatile in error handling with PG_TRY() / PG_CATCH().
PG_TRY and PG_CATCH
PostgreSQL lets you handle errors with the PG_TRY(), PG_CATCH(), and PG_END_TRY() macros. These rely on sigsetjmp() and siglongjmp(). When PG_TRY() runs, it calls sigsetjmp() to save the current execution state, including CPU registers. If an error occurs with ereport(ERROR, ...), siglongjmp() returns to this saved point, restores the registers, and the code continues in the PG_CATCH() block.
This is a problem for local variables. Sometimes, the compiler stores a local variable in a CPU register instead of memory. If you change such a variable inside the PG_TRY() block and an error happens, siglongjmp() will reset the register to its value from when sigsetjmp() was called. As a result, the PG_CATCH() block sees the old value. According to the C standard for setjmp() and longjmp() (and POSIX for sigsetjmp() and siglongjmp()), these variables have an indeterminate value unless you declare them as volatile, which makes the compiler keep them in memory.
“[…] the values of objects of automatic storage duration that are local to the function containing the invocation of the corresponding setjmp macro that do not have volatile-qualified type and have been changed between the setjmp invocation and longjmp call are indeterminate.”
— C11 standard, §7.13.2.1, N1570 draft
The PostgreSQL source code points out that this is a real problem and not only a theoretical one:
“Note: if a local variable of the function containing PG_TRY is modified in the PG_TRY section and used in the PG_CATCH section, that variable must be declared “volatile” for POSIX compliance. This is not mere pedantry; we have seen bugs from compilers improperly optimizing code away when such a variable was not marked. Beware that gcc’s -Wclobbered warnings are just about entirely useless for catching such oversights.”
— PostgreSQL source code, src/include/utils/elog.h
An example is the xmltext() function in xml.c (shortened):
xmlChar *volatile xmlbuf = NULL;
PG_TRY();
{
xmlbuf = xmlEncodeSpecialChars(NULL, xml_text2xmlChar(arg));
[...]
}
PG_CATCH();
{
if (xmlbuf)
xmlFree(xmlbuf);
[...]
PG_RE_THROW();
}
PG_END_TRY();
The buffer is allocated in the PG_TRY() block and freed in the PG_CATCH() block. Without volatile, the PG_CATCH() block could see the initial value NULL and the buffer would leak.
Note: The volatile keyword needs to be placed after the type: xmlChar *volatile xmlbuf declares a volatile pointer, which is what is needed here because the pointer itself is modified. In contrast, volatile xmlChar *xmlbuf declares a normal pointer to volatile data, which does not help.
Conclusion
Memory ordering bugs are hard to find because the code looks correct. The reordering does not happen in the source code, but in the compiler and the CPU. The compiler can reorder or even remove memory accesses, as long as a single thread cannot tell the difference. The CPU reorders memory accesses because of optimizations like store buffers and invalidate queues. How much reordering a CPU performs depends on its memory model: x86 only allows Store→Load reordering, while ARM allows all four types. This is why code that has worked on x86 for years can break on ARM.
PostgreSQL provides several tools to prevent these problems:
- Barriers:
pg_compiler_barrier()restricts only the compiler.pg_write_barrier()andpg_read_barrier()keep stores and loads in order. Usepg_memory_barrier()when a store must be visible before a later load, as inSetLatch(), or when a load must complete before a later store. On x86, onlypg_memory_barrier()needs a CPU instruction; the others are just compiler barriers. - Locks: Spinlocks and LWLocks keep memory accesses inside the critical section. Data protected by a lock does not need extra barriers. Using locks is often the simplest solution.
- Atomic operations: These prevent lost updates in read-modify-write actions like
counter++. But atomicity and ordering are not the same. Only operations with full barrier semantics, such aspg_atomic_fetch_add_u32(), also order nearby memory accesses. - Volatile: This tells the compiler to access the variable every time, which is important for local variables in
PG_TRY()/PG_CATCH(). However, it does not limit the CPU and does not replace memory barriers.
If you would like to learn more about memory barriers in general, I recommend reading the Memory Barriers: a Hardware View for Software Hackers paper by Paul E. McKenney. Furthermore, the README.barrier file in the PostgreSQL source code covers memory barriers in the context of PostgreSQL.