diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 85a0ce9..22f8540 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -1872,9 +1872,11 @@ WakeupWaiters(XLogRecPtr EndPos)
 	 */
 	while (head != NULL)
 	{
+		/* check comment in LWLockRelease() about barrier usage */
 		proc = head;
 		head = proc->lwWaitLink;
 		proc->lwWaitLink = NULL;
+		pg_write_barrier();
 		proc->lwWaiting = false;
 		PGSemaphoreUnlock(&proc->sem);
 	}
@@ -1966,9 +1968,11 @@ WALInsertSlotReleaseOne(int slotno)
 	 */
 	while (head != NULL)
 	{
+		/* check comment in LWLockRelease() about barrier usage */
 		proc = head;
 		head = proc->lwWaitLink;
 		proc->lwWaitLink = NULL;
+		pg_write_barrier();
 		proc->lwWaiting = false;
 		PGSemaphoreUnlock(&proc->sem);
 	}
diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c
index 82ef440..98c4845 100644
--- a/src/backend/storage/lmgr/lwlock.c
+++ b/src/backend/storage/lmgr/lwlock.c
@@ -28,6 +28,7 @@
 #include "miscadmin.h"
 #include "pg_trace.h"
 #include "replication/slot.h"
+#include "storage/barrier.h"
 #include "storage/ipc.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
@@ -944,10 +945,21 @@ LWLockRelease(LWLock *l)
 	 */
 	while (head != NULL)
 	{
+		/*
+		 * Use a write barrier to prevent the compiler from reordering the
+		 * store to lwWaitLink with the store to lwWaiting which could cause
+		 * problems when the to-be-woken-up backend wakes up spuriously and
+		 * writes to lwWaitLink when acquiring a new lock. That could corrupt
+		 * the list this backend is traversing leading to backends stuck
+		 * waiting for a lock. A write barrier is sufficient as the read side
+		 * only accesses the data while holding a spinlock which acts as a
+		 * full barrier.
+		 */
 		LOG_LWDEBUG("LWLockRelease", T_NAME(l), T_ID(l), "release waiter");
 		proc = head;
 		head = proc->lwWaitLink;
 		proc->lwWaitLink = NULL;
+		pg_write_barrier();
 		proc->lwWaiting = false;
 		PGSemaphoreUnlock(&proc->sem);
 	}
