diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index 27cb6307581..0ab95bd3d8e 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -37,6 +37,7 @@
 #include "miscadmin.h"
 #include "nodes/makefuncs.h"
 #include "parser/parse_type.h"
+#include "replication/syncrep.h"
 #include "storage/lmgr.h"
 #include "storage/proc.h"
 #include "storage/smgr.h"
@@ -812,6 +813,22 @@ nextval_internal(Oid relid, bool check_permissions)
 		PageSetLSN(page, recptr);
 	}
 
+	/*
+	 * Make sure the WAL for the sequence is properly flushed, before returning
+	 * the nextval result. For sessions that did not generate WAL (and so use a
+	 * cached value), this ensures the WAL generated by other sessions reaches
+	 * disk. Also, wait for sync replica.
+	 * 
+	 */
+	if (RelationNeedsWAL(seqrel))
+	{
+		XLogRecPtr	recptr = PageGetLSN(page);
+
+		XLogFlush(recptr);
+
+		SyncRepWaitForLSN(recptr, true);
+	}
+
 	/* Now update sequence tuple to the intended final state */
 	seq->last_value = last;		/* last fetched number */
 	seq->is_called = true;
