diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index eb2158d9e1e53611f960195600686ba72312f379..a2083dcd9a7ac3a5c0931e2815430cc06b1ec9e5 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2669,6 +2669,15 @@ main(int argc, char *argv[])
 		"pg_stat_tmp"
 	};
 
+	/*
+	 * Ensure that buffering behavior of stdout and stderr matches what it is
+	 * in interactive usage (at least on most platforms).  This prevents
+	 * unexpected output ordering when, eg, output is redirected to a file.
+	 * POSIX says we must do this before any other usage of these files.
+	 */
+	setvbuf(stdout, NULL, _IOLBF, 0);
+	setvbuf(stderr, NULL, _IONBF, 0);
+
 	progname = get_progname(argv[0]);
 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));