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 bef...

