Subject: Built-in connection pooler

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 24 Jan 2019 20:14:41 +0300

Hi hacker,

I am working for some time under built-in connection pooler for Postgres:
https://www.postgresql.org/message-id/flat/a866346d-5582-e8e8-2492-fd32732b0783%40postgrespro.ru#b1c354d5cf937893a75954e1e77f81f5

Unlike existed external pooler, this solution supports session semantic 
for pooled connections: you can use temporary tables, prepared 
statements, GUCs,...
But to make it possible I need to store/restore session context.
It is not so difficult, but it requires significant number of changes in 
Postgres code.
It will be committed in PgProEE-12 version of Postgres Professional 
version of Postgres,
but I realize that there are few changes to commit it to mainstream 
version of Postgres.

Dimitri Fontaine proposed to develop much simpler version of pooler 
which can be community:

> The main idea I want to pursue is the following:
>
>    - only solve the “idle connection” problem, nothing else, making idle connection basically free
>    - implement a layer in between a connection and a session, managing a “client backend” pool
>    - use the ability to give a socket to another process, as you did, so that the pool is not a proxy
>    - allow re-using of a backend for a new session only when it is safe to do so

Unfortunately, we have not found a way to support SSL connections with 
socket redirection.
So I have implemented solution with traditional proxy approach.
If client changes session context (creates temporary tables, set GUC 
values, prepare statements,...) then its backend becomes "tainted"
and is not more participate in pooling. It is now dedicated to this 
backend. But it still receives data through proxy.
Once this client is disconnected, tainted backend is terminated.

Built-in proxy accepts connection on special port (by default 6543).
If you connect to standard port, then normal Postgres backends will be 
launched and there is no difference with vanilla Postgres .
And if you connect to proxy port, then connection is redirected to one 
of proxy workers which then perform scheduling of all sessions, assigned 
to it.
There is currently on migration of sessions between proxies. There are 
three policies of assigning session to proxy:
random, round-robin and load-balancing.

The main differences with pgbouncer&K are that:

1. It is embedded and requires no extra steps for installation and 
configurations.
2. It is not single threaded (no bottleneck)
3. It supports all clients (if client needs session semantic, then it 
will be implicitly given dedicated backend)

Some performance results (pgbench -S -n):

#Connections
	Proxy
	Proxy/SSL
	Direct
	Direct/SSL
1
	13752
	12396
	17443
	15762
10
	53415
	59615
	68334
	85885
1000
	60152
	20445
	60003
	24047

Proxy configuration is the following:

session_pool_size = 4
connection_proxies = 2

postgres=# select * from pg_pooler_state();
  pid  | n_clients | n_ssl_clients | n_pools | n_backends | 
n_dedicated_backends | tx_bytes | rx_bytes | n_transactions
------+-----------+---------------+---------+------------+----------------------+----------+----------+---------------- 

  1310 |         1 |             0 |       1 |          4 
|                    0 | 10324739 |  9834981 |         156388
  1311 |         0 |             0 |       1 |          4 
|                    0 | 10430566 |  9936634 |         158007
(2 rows)

This implementation contains much less changes to Postgres core (it is 
more like invoking pgbouncer as Postgres worker).
The main things I have added are:
1. Mechanism for sending socket to a process (needed to redirect 
connection to proxy)
2. Support of edge pooling mode for epoll (needed to multiplex reads and 
writes)
3. Library libpqconn for establishing libpq connection from core

Proxy version of built-in connection pool is in conn_proxy branch in the 
following GIT repository:
https://github.com/postgrespro/postgresql.builtin_pool.git

Also I attach patch to the master to this mail.
Will be please to receive your comments.

-- 
Konstantin Knizhnik
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index e94b305..ee12562 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -704,6 +704,123 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-max-sessions" xreflabel="max_sessions">
+      <term><varname>max_sessions</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>max_sessions</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          The maximum number of client sessions that can be handled by
+          one connection proxy when session pooling is switched on.
+          This parameter does not add any memory or CPU overhead, so
+          specifying a large <varname>max_sessions</varname> value
+          does not affect performance.
+          If the <varname>max_sessions</varname> limit is reached new connection are not accepted.
+        </para>
+        <para>
+          The default value is 1000. This parameter can only be set at server start.
+       </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-session-pool-size" xreflabel="session_pool_size">
+      <term><varname>session_pool_size</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>session_pool_size</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          Enables session pooling and defines the maximum number of
+          backends that can be used by client sessions for each database/user combination.
+          Launched non-tainted backends are never terminated even if there are no active sessions.
+          Backend is considered as tainted if client updates GUCs, creates temporary table or prepared statements.
+          Tainted backend can server only one client.
+        </para>
+        <para>
+          The default value is 10, so up to 10 backends will server each database,
+        </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-proxy-port" xreflabel="proxy_port">
+      <term><varname>proxy_port</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>proxy_port</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          Sets the TCP port for the connection pooler.
+          Clients connected to main "port" will be assigned dedicated backends,
+          while client connected to proxy port will be connected to backends through proxy which
+          performs transaction level scheduling. 
+       </para>
+        <para>
+          The default value is 6543.
+        </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-connection-proxies" xreflabel="connection_proxies">
+      <term><varname>connection_proxies</varname> (<type>integer</type>)
+      <indexterm>
+       <primary><varname>connection_proxies</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          Sets number of connection proxies.
+          Postmaster spawns separate worker process for each proxy. Postmaster scatters connections between proxies using one of scheduling policies (round-robin, random, load-balancing)."
+		 "Each proxy launches its own subset of backends. So maximal number of non-tainted backends is "
+		  "session_pool_size*connection_proxies*databases*roles.
+       </para>
+        <para>
+          The default value is 0, so session pooling is disabled.
+        </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-session-schedule" xreflabel="session_schedule">
+      <term><varname>session_schedule</varname> (<type>enum</type>)
+      <indexterm>
+       <primary><varname>session_schedule</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          Specifies scheduling policy for assigning session to proxies in case of
+          connection pooling. Default policy is <literal>round-robin</literal>.
+        </para>
+        <para>
+          With <literal>round-robin</literal> policy postmaster cyclicly scatter sessions between proxies.
+        </para>
+        <para>
+          With <literal>random</literal> policy postmaster randomly choose proxy for new session.
+        </para>
+        <para>
+          With <literal>load-balancing</literal> policy postmaster choose proxy with lowest load average.
+          Load average of proxy is estimated by number of clients connection assigned to this proxy with extra weight for SSL connections.
+       </para>
+      </listitem>
+     </varlistentry>
+
+     <varlistentry id="guc-restart-pooler-on-reload" xreflabel="restart_pooler_on_reload">
+      <term><varname>restart_pooler_on_reload</varname> (<type>string</type>)
+      <indexterm>
+       <primary><varname>restart_pooler_on_reload</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+        <para>
+          Restart session pool workers once <function>pg_reload_conf()</function> is called.
+          The default value is <literal>false</literal>.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-unix-socket-directories" xreflabel="unix_socket_directories">
       <term><varname>unix_socket_directories</varname> (<type>string</type>)
       <indexterm>
diff --git a/doc/src/sgml/connpool.sgml b/doc/src/sgml/connpool.sgml
new file mode 100644
index 0000000..07f4202
--- /dev/null
+++ b/doc/src/sgml/connpool.sgml
@@ -0,0 +1,174 @@
+<!-- doc/src/sgml/connpool.sgml -->
+
+ <chapter id="connection-pooling">
+  <title>Connection pooling</title>
+
+  <indexterm zone="connection-pooling">
+   <primary>built-in connection pool proxy</primary>
+  </indexterm>
+
+  <para>
+    <productname>PostgreSQL</productname> spawns a separate process (backend) for each client.
+    For large number of clients such model can cause consumption of large number of system
+    resources and lead to significant performance degradation, especially at computers with large
+    number of CPU cores. The reason is high contention between backends for postgres resources.
+    Also size of many Postgres internal data structures are proportional to the number of
+    active backends as well as complexity of algorithms for this data structures.
+  </para>
+
+  <para>
+    This is why most of production Postgres installation are using some kind of connection pooling:
+    pgbouncer, J2EE, odyssey,... But external connection pooler requires additional efforts for installation,
+    configuration and maintenance. Also pgbouncer (the most popular connection pooler for Postgres) is
+    single-threaded and so can be bottleneck for highload system, so multiple instances of pgbouncer have to be launched.
+  </para>
+
+  <para>
+    Starting from version 12 <productname>PostgreSQL</productname> provides built-in connection pooler.
+    This chapter describes architecture and usage of built-in connection pooler.
+  </para>
+
+ <sect1 id="how-connection-pooler-works">
+  <title>How Built-in Connection Pooler Works</title>
+
+  <para>
+    Built-in connection pooler spawns one or more proxy processes which connect clients and backends.
+    Number of proxy processes is controlled by <varname>connection_proxies</varname> configuration parameter.
+    To avoid substantial changes in Postgres locking mechanism, only transaction level pooling policy is implemented.
+    It means that pooler is able to reschedule backend to another session only when it completed the current transaction.
+  </para>
+
+  <para>
+    As far as each Postgres backend is able to work only with single database, each proxy process maintains
+    hash table of connections pools for each pair of <literal>dbname,role</literal>.
+    Maximal number of backends which can be spawned by connection pool is limited by
+    <varname>session_pool_size</varname> configuration variable.
+    So maximal number of non-dedicated backends in pooling mode is limited by
+    <varname>connection_proxies</varname>*<varname>session_pool_size</varname>*<literal>#databases</literal>*<literal>#roles</literal>.
+  </para>
+
+  <para>
+    To minimize number of changes in Postgres core, built-in connection pooler is not trying to save/restore
+    session context. If session context is modified by client application
+    (changing values of configuration variables (GUCs), creating temporary tables, preparing statements, advisory locking),
+    then backend executing this session is considered to be <emphasis>tainted</emphasis>.
+    It is now dedicated to this session and can not be rescheduled to other session.
+    Once this session is terminated, backend is terminated as well.
+    Non-tainted backends are not terminated even if there are no more connected sessions.
+  </para>
+
+  <para>
+    Built-in connection pooler is accepted connections on separate port (<varname>proxy_port</varname> configuration option, default value is 6543).
+    If client is connected to postgres through standard port (<varname>port</varname> configuration option, default value is 5432), then normal (<emphasis>dedicated</emphasis>) backend is created. It works only
+    with this client and is terminated when client is disconnected. Standard port is also used by proxy itself to
+    launch new worker backends. It means that to enable connection pooler Postgres should be configured
+    to accept local connections (<literal>pg_hba.conf</literal> file).
+  </para>
+
+  <para>
+    If client application is connected through proxy port, then its communication with backend is always
+    performed through proxy. Even if it changes session context and backend becomes <emphasis>tainted</emphasis>,
+    still all traffic between this client and backend comes through proxy.
+  </para>
+
+  <para>
+    Postmaster accepts connections on proxy port and redirects it to one of connection proxies.
+    Right now sessions and bounded to proxy and can not migrate between them.
+    To provide uniform load balancing of proxies, postmaster is using one of three scheduling policies:
+    <literal>round-robin</literal>, <literal>random</literal> and <literal>load-balancing</literal>.
+    In the last case postmaster will choose proxy with smallest number of already attached clients, with
+    extra weight added to SSL connections (which consume more CPU).
+  </para>
+
+ </sect1>
+
+ <sect1 id="connection-pooler-configuration">
+  <title>Built-in Connection Pooler Configuration</title>
+
+  <para>
+    There are four main configuration variables controlling connection pooler:
+    <varname>session_pool_size</varname>, <varname>connection_proxies</varname>, <varname>max_sessions</varname> and <varname>proxy_port</varname>.
+    Connection pooler is enabled if all of them are non-zero.
+  </para>
+
+  <para>
+    <varname>connection_proxies</varname> specifies number of connection proxy processes which will be spawned.
+    Default value is zero, so connection pooling is disabled by default.
+  </para>
+
+  <para>
+    <varname>session_pool_size</varname> specifies maximal number of backends per connection pool. Maximal number of laucnhed non-dedicated backends in pooling mode is limited by
+    <varname>connection_proxies</varname>*<varname>session_pool_size</varname>*<literal>#databases</literal>*<literal>#roles</literal>.
+    If number of backends is too small, then server will not be able to utilize all system resources.
+    But too large value can cause degradation of performance because of large snapshots and lock contention.
+  </para>
+
+  <para>
+    <varname>max_sessions</varname>parameter specifies maximal number of sessions which can be handled by one connection proxy.
+    Actually it affects only size of wait event set and so can be large enough without any  essential negative impact on system resources consumption.
+    Default value is 1000. So maximal number of connections to one database/role is limited by <varname>connection_proxies</varname>*<varname>session_pool_size</varname>*<varname>max_sessions</varname>.
+  </para>
+
+  <para>
+    Connection proxy accepts connections on special port, defined by <varname>proxy_port</varname>.
+    Default value is 6543, but it can be changed to standard Postgres 4321, so by default all connections to the databases will be pooled.
+    But it is still necessary to have a port for direct connections to the database (dedicated backends).
+    It is needed for connection pooler itself to launch worker backends.
+  </para>
+
+  <para>
+    Postmaster scatters sessions between proxies using one of three available scheduling policies:
+    <literal>round-robin</literal>, <literal>random</literal> and <literal>load-balancing</literal>.
+    Policy can be set using <varname>session_schedule</varname> configuration variable. Default policy is
+    <literal>round-robin</literal> which cause cyclic distribution of sessions between proxies.
+    It should work well in case of more or less uniform workload.
+    The smartest policy is <literal>load-balancing</literal> which tries to choose least loaded proxy
+    based on the available statistic. It is possible to monitor proxies state using <function>pg_pooler_state()</function> function, which returns information about number of clients, backends and pools for each proxy as well
+    as some statistic information about number of proceeded transactions and amount of data
+    sent from client to backends (<varname>rx_bytes</varname>) and from backends to clients (<varname>tx_bytes</varname>).
+  </para>
+
+  <para>
+    As far as pooled backends are not terminated on client exist, it will not
+    be possible to drop database to which them are connected.  It can be achieved without server restart using <varname>restart_pooler_on_reload</varname> variable. Setting this variable to <literal>true</literal> cause shutdown of all pooled backends after execution of <function>pg_reload_conf()</function> function. Then it will be possible to drop database.
+  </para>
+
+ </sect1>
+
+ <sect1 id="connection-pooler-constraints">
+  <title>Built-in Connection Pooler Pros and Cons</title>
+
+  <para>
+    Unlike pgbouncer and other external connection poolera, built-in connection pooler doesn't require installation and configuration of some other components.
+    Also it doesn't introduce any limitations for clients: existed clients can work through proxy and don't notice any difference.
+    If client application requires session context, then it will be served by dedicated backend. Such connection will not participate in
+    connection pooling but it will correctly work. This is the main difference with pgbouncer,
+    which may cause incorrect behavior of client application in case of using other session level pooling policy.
+    And if application is not changing session context, then it can be implicitly pooled, reducing number of active backends.
+  </para>
+
+  <para>
+    The main limitation of current built-in connection pooler implementation is that it is not able to save/resume session context.
+    Although it is not so difficult to do, but it requires more changes in Postgres core. So developers of client applications still have a choice
+    either to avoid using session-specific operations either not to use pooling. For example, using prepared statements can improve speed of simple queries
+    up to two times. But prepared statements can not be handled by pooled backend, so if all clients are using prepared statements, then there will be no connection pooling
+    even if connection pooling is enabled.
+  </para>
+
+  <para>
+    Redirecting connections through connection proxy definitely have negative effect on total system performance and especially latency.
+    Overhead of connection proxing depends on too many factors, such as characteristics of external and internal networks, complexity of queries and size of returned result set.
+    Pgbench benchmark in select-only mode shows almost two times worser performance for local connections through connection pooler comparing with direct local connections when
+    number of connections is small enough (10). For much larger number of connections (when pooling is actually required), pooling mode outperforms direct connection mode.
+  </para>
+
+  <para>
+    Another obvious limitation of transaction level pooling is that long living transaction can cause starvation of
+    other clients. It greatly depends on application design. If application opens database transaction and then waits for user input or some other external event, then backend can be in <emphasis>idle-in-transaction</emphasis>
+    state for long enough time. And such backend can not be rescheduled for some another session.
+    The obvious recommendation is to avoid long-living transaction and setup <varname>idle_in_transaction_session_timeout</varname> to implicitly abort such transactions.
+  </para>
+
+ </sect1>
+
+ </chapter>
diff --git a/doc/src/sgml/filelist.sgml b/doc/src/sgml/filelist.sgml
index 5dfdf54..8747b7f 100644
--- a/doc/src/sgml/filelist.sgml
+++ b/doc/src/sgml/filelist.sgml
@@ -29,6 +29,7 @@
 <!ENTITY syntax     SYSTEM "syntax.sgml">
 <!ENTITY textsearch SYSTEM "textsearch.sgml">
 <!ENTITY typeconv   SYSTEM "typeconv.sgml">
+<!ENTITY connpool   SYSTEM "connpool.sgml">
 
 <!-- administrator's guide -->
 <!ENTITY backup        SYSTEM "backup.sgml">
diff --git a/doc/src/sgml/postgres.sgml b/doc/src/sgml/postgres.sgml
index 96d196d..32d0c77 100644
--- a/doc/src/sgml/postgres.sgml
+++ b/doc/src/sgml/postgres.sgml
@@ -109,6 +109,7 @@
   &mvcc;
   &perform;
   &parallel;
+  &connpool;
 
  </part>
 
diff --git a/src/Makefile b/src/Makefile
index bcdbd95..196ca8c 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -23,6 +23,7 @@ SUBDIRS = \
 	interfaces \
 	backend/replication/libpqwalreceiver \
 	backend/replication/pgoutput \
+	backend/postmaster/libpqconn \
 	fe_utils \
 	bin \
 	pl \
diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c
index 6036b73..99d2da9 100644
--- a/src/backend/commands/prepare.c
+++ b/src/backend/commands/prepare.c
@@ -30,6 +30,7 @@
 #include "parser/parse_expr.h"
 #include "parser/parse_type.h"
 #include "rewrite/rewriteHandler.h"
+#include "storage/proc.h"
 #include "tcop/pquery.h"
 #include "tcop/utility.h"
 #include "utils/builtins.h"
@@ -467,6 +468,7 @@ StorePreparedStatement(const char *stmt_name,
 											  stmt_name,
 											  HASH_ENTER,
 											  &found);
+	MyProc->is_tainted = true;
 
 	/* Shouldn't get a duplicate entry */
 	if (found)
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 588c1ec..f6e1daf 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -553,6 +553,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
+	if (stmt->relation->relpersistence != RELPERSISTENCE_TEMP
+		&& stmt->oncommit != ONCOMMIT_DROP)
+		MyProc->is_tainted = true;
+
 	if (stmt->partspec != NULL)
 	{
 		if (relkind != RELKIND_RELATION)
diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index 0c9593d..4a6d01d 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -195,15 +195,13 @@ pq_init(void)
 {
 	/* initialize state variables */
 	PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
-	PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
+	if (!PqSendBuffer)
+		PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
 	PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
 	PqCommBusy = false;
 	PqCommReadingMsg = false;
 	DoingCopyOut = false;
 
-	/* set up process-exit hook to close the socket */
-	on_proc_exit(socket_close, 0);
-
 	/*
 	 * In backends (as soon as forked) we operate the underlying socket in
 	 * nonblocking mode and use latches to implement blocking semantics if
@@ -220,6 +218,11 @@ pq_init(void)
 				(errmsg("could not set socket to nonblocking mode: %m")));
 #endif
 
+	if (FeBeWaitSet)
+		FreeWaitEventSet(FeBeWaitSet);
+	else
+		on_proc_exit(socket_close, 0);
+
 	FeBeWaitSet = CreateWaitEventSet(TopMemoryContext, 3);
 	AddWaitEventToSet(FeBeWaitSet, WL_SOCKET_WRITEABLE, MyProcPort->sock,
 					  NULL, NULL);
@@ -227,6 +230,7 @@ pq_init(void)
 	AddWaitEventToSet(FeBeWaitSet, WL_POSTMASTER_DEATH, -1, NULL, NULL);
 }
 
+
 /* --------------------------------
  *		socket_comm_reset - reset libpq during error recovery
  *
@@ -329,7 +333,7 @@ socket_close(int code, Datum arg)
 int
 StreamServerPort(int family, char *hostName, unsigned short portNumber,
 				 char *unixSocketDir,
-				 pgsocket ListenSocket[], int MaxListen)
+				 pgsocket ListenSocket[], int ListenPort[], int MaxListen)
 {
 	pgsocket	fd;
 	int			err;
@@ -593,6 +597,7 @@ StreamServerPort(int family, char *hostName, unsigned short portNumber,
 							familyDesc, addrDesc, (int) portNumber)));
 
 		ListenSocket[listen_index] = fd;
+		ListenPort[listen_index] = portNumber;
 		added++;
 	}
 
diff --git a/src/backend/port/Makefile b/src/backend/port/Makefile
index f4120be..e0cdd9e 100644
--- a/src/backend/port/Makefile
+++ b/src/backend/port/Makefile
@@ -21,7 +21,7 @@ subdir = src/backend/port
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
-OBJS = atomics.o pg_sema.o pg_shmem.o $(TAS)
+OBJS = atomics.o pg_sema.o pg_shmem.o send_sock.o $(TAS)
 
 ifeq ($(PORTNAME), win32)
 SUBDIRS += win32
diff --git a/src/backend/port/send_sock.c b/src/backend/port/send_sock.c
new file mode 100644
index 0000000..83c97c5
--- /dev/null
+++ b/src/backend/port/send_sock.c
@@ -0,0 +1,164 @@
+/*-------------------------------------------------------------------------
+ *
+ * send_sock.c
+ *	  Send socket descriptor to another process
+ *
+ * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/backend/port/send_sock.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifdef WIN32
+typedef struct
+{
+	SOCKET origsocket;
+	WSAPROTOCOL_INFO wsainfo;
+} InheritableSocket;
+#endif
+
+/*
+ * Send socket descriptor "sock" to backend process through Unix socket "chan"
+ */
+int
+pg_send_sock(pgsocket chan, pgsocket sock, pid_t pid)
+{
+#ifdef WIN32
+	InheritableSocket dst;
+	size_t rc;
+	dst.origsocket = sock;
+	if (WSADuplicateSocket(sock, pid, &dst.wsainfo) != 0)
+	{
+		ereport(FATAL,
+				(errmsg("could not duplicate socket %d for use in backend: error code %d",
+						(int)sock, WSAGetLastError())));
+		return -1;
+	}
+	rc = send(chan, &dst, sizeof(dst), 0);
+	if (rc != sizeof(dst))
+	{
+		ereport(FATAL,
+				(errmsg("Failed to send inheritable socket: rc=%d, error code %d",
+						(int)rc, WSAGetLastError())));
+		return -1;
+	}
+	return 0;
+#else
+	struct msghdr msg = { 0 };
+	struct iovec io;
+	struct cmsghdr * cmsg;
+    char buf[CMSG_SPACE(sizeof(sock))];
+    memset(buf, '\0', sizeof(buf));
+
+    /* On Mac OS X, the struct iovec is needed, even if it points to minimal data */
+    io.iov_base = "";
+	io.iov_len = 1;
+
+    msg.msg_iov = &io;
+    msg.msg_iovlen = 1;
+    msg.msg_control = buf;
+    msg.msg_controllen = sizeof(buf);
+
+    cmsg = CMSG_FIRSTHDR(&msg);
+	if (!cmsg)
+		return PGINVALID_SOCKET;
+
+    cmsg->cmsg_level = SOL_SOCKET;
+    cmsg->cmsg_type = SCM_RIGHTS;
+    cmsg->cmsg_len = CMSG_LEN(sizeof(sock));
+
+    memcpy(CMSG_DATA(cmsg), &sock, sizeof(sock));
+    msg.msg_controllen = cmsg->cmsg_len;
+
+    while (sendmsg(chan, &msg, 0) < 0)
+	{
+		if (errno != EINTR)
+			return PGINVALID_SOCKET;
+	}
+
+	return 0;
+#endif
+}
+
+
+/*
+ * Receive socket descriptor from postmaster process through Unix socket "chan"
+ */
+pgsocket
+pg_recv_sock(pgsocket chan)
+{
+#ifdef WIN32
+	InheritableSocket src;
+	SOCKET s;
+	size_t rc = recv(chan, &src, sizeof(src), 0);
+	if (rc != sizeof(src))
+	{
+		ereport(FATAL,
+				(errmsg("Failed to receive inheritable socket: rc=%d, error code %d",
+						(int)rc, WSAGetLastError())));
+	}
+	s = WSASocket(FROM_PROTOCOL_INFO,
+				  FROM_PROTOCOL_INFO,
+				  FROM_PROTOCOL_INFO,
+				  &src.wsainfo,
+				  0,
+				  0);
+	if (s == INVALID_SOCKET)
+	{
+		ereport(FATAL,
+				(errmsg("could not create inherited socket: error code %d\n",
+						WSAGetLastError())));
+	}
+
+	/*
+	 * To make sure we don't get two references to the same socket, close
+	 * the original one. (This would happen when inheritance actually
+	 * works..
+	 */
+	closesocket(src.origsocket);
+	return s;
+#else
+	struct msghdr msg = {0};
+    char c_buffer[256];
+    char m_buffer[256];
+    struct iovec io;
+	struct cmsghdr * cmsg;
+	pgsocket sock;
+
+    io.iov_base = m_buffer;
+	io.iov_len = sizeof(m_buffer);
+    msg.msg_iov = &io;
+    msg.msg_iovlen = 1;
+
+    msg.msg_control = c_buffer;
+    msg.msg_controllen = sizeof(c_buffer);
+
+    while (recvmsg(chan, &msg, 0) < 0)
+	{
+		if (errno != EINTR)
+			return PGINVALID_SOCKET;
+	}
+
+    cmsg = CMSG_FIRSTHDR(&msg);
+	if (!cmsg)
+		return PGINVALID_SOCKET;
+
+    memcpy(&sock, CMSG_DATA(cmsg), sizeof(sock));
+
+	pg_set_noblock(sock);
+
+    return sock;
+#endif
+}
diff --git a/src/backend/port/win32/socket.c b/src/backend/port/win32/socket.c
index af35cfb..5890445 100644
--- a/src/backend/port/win32/socket.c
+++ b/src/backend/port/win32/socket.c
@@ -690,3 +690,65 @@ pgwin32_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, c
 		memcpy(writefds, &outwritefds, sizeof(fd_set));
 	return nummatches;
 }
+
+int pgwin32_socketpair(int domain, int type, int protocol, SOCKET socks[2])
+{
+    union {
+       struct sockaddr_in inaddr;
+       struct sockaddr addr;
+    } a;
+    SOCKET listener;
+    int e;
+    socklen_t addrlen = sizeof(a.inaddr);
+    DWORD flags = 0;
+    int reuse = 1;
+
+    socks[0] = socks[1] = -1;
+
+    listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    if (listener == -1)
+        return SOCKET_ERROR;
+
+    memset(&a, 0, sizeof(a));
+    a.inaddr.sin_family = AF_INET;
+    a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+    a.inaddr.sin_port = 0;
+
+    for (;;) {
+        if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,
+               (char*) &reuse, (socklen_t) sizeof(reuse)) == -1)
+            break;
+        if  (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
+            break;
+
+        memset(&a, 0, sizeof(a));
+        if  (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
+            break;
+        a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+        a.inaddr.sin_family = AF_INET;
+
+        if (listen(listener, 1) == SOCKET_ERROR)
+            break;
+
+        socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, flags);
+        if (socks[0] == -1)
+            break;
+        if (connect(socks[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
+            break;
+
+        socks[1] = accept(listener, NULL, NULL);
+        if (socks[1] == -1)
+            break;
+
+        closesocket(listener);
+        return 0;
+    }
+
+    e = WSAGetLastError();
+    closesocket(listener);
+    closesocket(socks[0]);
+    closesocket(socks[1]);
+    WSASetLastError(e);
+    socks[0] = socks[1] = -1;
+    return SOCKET_ERROR;
+}
diff --git a/src/backend/postmaster/Makefile b/src/backend/postmaster/Makefile
index 71c2321..9622ee7 100644
--- a/src/backend/postmaster/Makefile
+++ b/src/backend/postmaster/Makefile
@@ -13,6 +13,6 @@ top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
 OBJS = autovacuum.o bgworker.o bgwriter.o checkpointer.o fork_process.o \
-	pgarch.o pgstat.o postmaster.o startup.o syslogger.o walwriter.o
+	pgarch.o pgstat.o postmaster.o startup.o syslogger.o walwriter.o proxy.o
 
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/postmaster/libpqconn/Makefile b/src/backend/postmaster/libpqconn/Makefile
new file mode 100644
index 0000000..f05b727
--- /dev/null
+++ b/src/backend/postmaster/libpqconn/Makefile
@@ -0,0 +1,35 @@
+#-------------------------------------------------------------------------
+#
+# Makefile--
+#    Makefile for src/backend/postmaster/libpqconn
+#
+# IDENTIFICATION
+#    src/backend/postmaster/libpqconn/Makefile
+#
+#-------------------------------------------------------------------------
+
+subdir = src/backend/postmaster/libpqconn
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+
+override CPPFLAGS := -I$(srcdir) -I$(libpq_srcdir) $(CPPFLAGS)
+
+OBJS = libpqconn.o $(WIN32RES)
+SHLIB_LINK_INTERNAL = $(libpq)
+SHLIB_LINK = $(filter -lintl, $(LIBS))
+SHLIB_PREREQS = submake-libpq
+PGFILEDESC = "libpqconn - open libpq connection"
+NAME = libpqconn
+
+all: all-shared-lib
+
+include $(top_srcdir)/src/Makefile.shlib
+
+install: all installdirs install-lib
+
+installdirs: installdirs-lib
+
+uninstall: uninstall-lib
+
+clean distclean maintainer-clean: clean-lib
+	rm -f $(OBJS)
diff --git a/src/backend/postmaster/libpqconn/libpqconn.c b/src/backend/postmaster/libpqconn/libpqconn.c
new file mode 100644
index 0000000..8edd93d
--- /dev/null
+++ b/src/backend/postmaster/libpqconn/libpqconn.c
@@ -0,0 +1,45 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpqconn.c
+ *
+ * This file provides a way to establish connection to postgres instanc from backend.
+ *
+ * Portions Copyright (c) 2010-2018, PostgreSQL Global Development Group
+ *
+ *
+ * IDENTIFICATION
+ *	  src/backend/postmaster/libpqconn/libpqconn.c
+ *
+ *-------------------------------------------------------------------------
+ */
+#include "postgres.h"
+
+#include <unistd.h>
+#include <sys/time.h>
+
+#include "fmgr.h"
+#include "libpq-fe.h"
+#include "postmaster/postmaster.h"
+
+PG_MODULE_MAGIC;
+
+static void*
+libpq_connectdb(char const* keywords[], char const* values[])
+{
+	PGconn* conn = PQconnectdbParams(keywords, values, false);
+	if (!conn || PQstatus(conn) != CONNECTION_OK)
+	{
+		ereport(WARNING,
+				(errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
+				 errmsg("could not setup local connect to server"),
+				 errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
+		return NULL;
+	}
+	return conn;
+}
+
+void _PG_init(void)
+{
+	LibpqConnectdbParams = libpq_connectdb;
+}
+
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index eedc617..1fd5878 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -114,6 +114,7 @@
 #include "postmaster/fork_process.h"
 #include "postmaster/pgarch.h"
 #include "postmaster/postmaster.h"
+#include "postmaster/proxy.h"
 #include "postmaster/syslogger.h"
 #include "replication/logicallauncher.h"
 #include "replication/walsender.h"
@@ -196,6 +197,9 @@ BackgroundWorker *MyBgworkerEntry = NULL;
 /* The socket number we are listening for connections on */
 int			PostPortNumber;
 
+/* The socket number we are listening for poolled connections on */
+int			ProxyPortNumber;
+
 /* The directory names for Unix socket(s) */
 char	   *Unix_socket_directories;
 
@@ -216,6 +220,7 @@ int			ReservedBackends;
 /* The socket(s) we're listening to. */
 #define MAXLISTEN	64
 static pgsocket ListenSocket[MAXLISTEN];
+static int      ListenPort[MAXLISTEN];
 
 /*
  * Set by the -o option
@@ -246,6 +251,18 @@ bool		enable_bonjour = false;
 char	   *bonjour_name;
 bool		restart_after_crash = true;
 
+typedef struct ConnectionProxy
+{
+	int pid;
+	pgsocket socks[2];
+} ConnectionProxy;
+
+ConnectionProxy* ConnectionProxies;
+static bool ConnectionProxiesStarted;
+static int CurrentConnectionProxy; /* index used for round-robin distribution of connections between proxies */
+
+void* (*LibpqConnectdbParams)(char const* keywords[], char const* values[]);
+
 /* PIDs of special child processes; 0 when not running */
 static pid_t StartupPID = 0,
 			BgWriterPID = 0,
@@ -413,7 +430,6 @@ static void BackendInitialize(Port *port);
 static void BackendRun(Port *port) pg_attribute_noreturn();
 static void ExitPostmaster(int status) pg_attribute_noreturn();
 static int	ServerLoop(void);
-static int	BackendStartup(Port *port);
 static int	ProcessStartupPacket(Port *port, bool SSLdone);
 static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options);
 static void processCancelRequest(Port *port, void *pkt);
@@ -435,6 +451,7 @@ static pid_t StartChildProcess(AuxProcType type);
 static void StartAutovacuumWorker(void);
 static void MaybeStartWalReceiver(void);
 static void InitPostmasterDeathWatchHandle(void);
+static void StartProxyWorker(int id);
 
 /*
  * Archiver is allowed to start up at the current postmaster state?
@@ -487,6 +504,8 @@ typedef struct
 {
 	Port		port;
 	InheritableSocket portsocket;
+	InheritableSocket proxySocket;
+	int         proxyId;
 	char		DataDir[MAXPGPATH];
 	pgsocket	ListenSocket[MAXLISTEN];
 	int32		MyCancelKey;
@@ -569,6 +588,48 @@ int			postmaster_alive_fds[2] = {-1, -1};
 HANDLE		PostmasterHandle;
 #endif
 
+static void
+StartConnectionProxies(void)
+{
+	if (SessionPoolSize > 0 && ConnectionProxiesNumber > 0 && !ConnectionProxiesStarted)
+	{
+		int i;
+		if (ConnectionProxies == NULL)
+		{
+			ConnectionProxies = malloc(sizeof(ConnectionProxy*)*ConnectionProxiesNumber);
+			for (i = 0; i < ConnectionProxiesNumber; i++)
+			{
+				if (socketpair(AF_UNIX, SOCK_STREAM, 0, ConnectionProxies[i].socks) < 0)
+					ereport(FATAL,
+							(errcode_for_file_access(),
+							 errmsg_internal("could not create socket pair for launching sessions: %m")));
+			}
+		}
+		for (i = 0; i < ConnectionProxiesNumber; i++)
+		{
+			StartProxyWorker(i);
+		}
+		ConnectionProxiesStarted = true;
+	}
+}
+
+/*
+ * Send signal to connection proxies
+ */
+static void
+StopConnectionProxies(int signal)
+{
+	if (ConnectionProxiesStarted)
+	{
+		int i;
+		for (i = 0; i < ConnectionProxiesNumber; i++)
+		{
+			signal_child(ConnectionProxies[i].pid, signal);
+		}
+		ConnectionProxiesStarted = false;
+	}
+}
+
 /*
  * Postmaster main entry point
  */
@@ -581,6 +642,9 @@ PostmasterMain(int argc, char *argv[])
 	bool		listen_addr_saved = false;
 	int			i;
 	char	   *output_config_variable = NULL;
+	bool        contains_localhost = false;
+	int         ports[2];
+	int         n_ports = 0;
 
 	InitProcessGlobals();
 
@@ -1013,6 +1077,11 @@ PostmasterMain(int argc, char *argv[])
 
 	on_proc_exit(CloseServerPorts, 0);
 
+	/* Listen on proxy socket only if session pooling is enabled */
+	if (ProxyPortNumber > 0 && ConnectionProxiesNumber > 0 && SessionPoolSize > 0)
+		ports[n_ports++] = ProxyPortNumber;
+	ports[n_ports++] = PostPortNumber;
+
 	if (ListenAddresses)
 	{
 		char	   *rawstring;
@@ -1036,32 +1105,36 @@ PostmasterMain(int argc, char *argv[])
 		foreach(l, elemlist)
 		{
 			char	   *curhost = (char *) lfirst(l);
-
-			if (strcmp(curhost, "*") == 0)
-				status = StreamServerPort(AF_UNSPEC, NULL,
-										  (unsigned short) PostPortNumber,
-										  NULL,
-										  ListenSocket, MAXLISTEN);
-			else
-				status = StreamServerPort(AF_UNSPEC, curhost,
-										  (unsigned short) PostPortNumber,
-										  NULL,
-										  ListenSocket, MAXLISTEN);
-
-			if (status == STATUS_OK)
+			for (i = 0; i < n_ports; i++)
 			{
-				success++;
-				/* record the first successful host addr in lockfile */
-				if (!listen_addr_saved)
+				int port = ports[i];
+				if (strcmp(curhost, "*") == 0)
+					status = StreamServerPort(AF_UNSPEC, NULL,
+											  (unsigned short) port,
+											  NULL,
+											  ListenSocket, ListenPort, MAXLISTEN);
+				else
+					status = StreamServerPort(AF_UNSPEC, curhost,
+											  (unsigned short) port,
+											  NULL,
+											  ListenSocket, ListenPort, MAXLISTEN);
+				contains_localhost |= strcmp(curhost, "localhost") == 0;
+
+				if (status == STATUS_OK)
 				{
-					AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
-					listen_addr_saved = true;
+					success++;
+					/* record the first successful host addr in lockfile */
+					if (!listen_addr_saved)
+					{
+						AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
+						listen_addr_saved = true;
+					}
 				}
+				else
+					ereport(WARNING,
+							(errmsg("could not create listen socket for \"%s\"",
+									curhost)));
 			}
-			else
-				ereport(WARNING,
-						(errmsg("could not create listen socket for \"%s\"",
-								curhost)));
 		}
 
 		if (!success && elemlist != NIL)
@@ -1130,29 +1203,32 @@ PostmasterMain(int argc, char *argv[])
 					 errmsg("invalid list syntax in parameter \"%s\"",
 							"unix_socket_directories")));
 		}
-
+		contains_localhost = true;
 		foreach(l, elemlist)
 		{
 			char	   *socketdir = (char *) lfirst(l);
+			for (i = 0; i < n_ports; i++)
+			{
+				int port = ports[i];
 
-			status = StreamServerPort(AF_UNIX, NULL,
-									  (unsigned short) PostPortNumber,
-									  socketdir,
-									  ListenSocket, MAXLISTEN);
+				status = StreamServerPort(AF_UNIX, NULL,
+										  (unsigned short) port,
+										  socketdir,
+										  ListenSocket, ListenPort, MAXLISTEN);
 
-			if (status == STATUS_OK)
-			{
-				success++;
-				/* record the first successful Unix socket in lockfile */
-				if (success == 1)
-					AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
+				if (status == STATUS_OK)
+				{
+					success++;
+					/* record the first successful Unix socket in lockfile */
+					if (success == 1)
+						AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
+				}
+				else
+					ereport(WARNING,
+							(errmsg("could not create Unix-domain socket in directory \"%s\"",
+									socketdir)));
 			}
-			else
-				ereport(WARNING,
-						(errmsg("could not create Unix-domain socket in directory \"%s\"",
-								socketdir)));
 		}
-
 		if (!success && elemlist != NIL)
 			ereport(FATAL,
 					(errmsg("could not create any Unix-domain sockets")));
@@ -1162,6 +1238,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
+	if (!contains_localhost && ProxyPortNumber > 0)
+	{
+		/* we need to accept local connections from proxy */
+		status = StreamServerPort(AF_UNSPEC, "localhost",
+								  (unsigned short) PostPortNumber,
+								  NULL,
+								  ListenSocket, ListenPort, MAXLISTEN);
+		if (status != STATUS_OK)
+		{
+			ereport(WARNING,
+					(errmsg("could not create listen socket for locahost")));
+		}
+	}
+
 	/*
 	 * check that we have some socket to listen on
 	 */
@@ -1383,6 +1473,8 @@ PostmasterMain(int argc, char *argv[])
 	/* Some workers may be scheduled to start now */
 	maybe_start_bgworkers();
 
+	StartConnectionProxies();
+
 	status = ServerLoop();
 
 	/*
@@ -1620,6 +1712,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
+ * This function tries to estimate workload of proxy.
+ * We have a lot of information about proxy state in ProxyState array:
+ * total number of clients, SSL clients, backends, traffic, number of transactions,...
+ * So in principle it is possible to implement much more sophisticated evaluation function,
+ * but right now we take in account only number of clients and SSL connections (which requires much more CPU)
+ */
+static uint64
+GetConnectionProxyWorkload(int id)
+{
+	return ProxyState[id].n_clients + ProxyState[id].n_ssl_clients*3;
+}
+
+/**
+ * Choose connection pool for this session.
+ * Right now sessions can not be moved between pools (in principle it is not so difficult to implement it),
+ * so to support order balancing we should do dome smart work here.
+ */
+static ConnectionProxy*
+SelectConnectionProxy(void)
+{
+	int i;
+	uint64 min_workload;
+	int least_loaded_proxy;
+
+	switch (SessionSchedule)
+	{
+	  case SESSION_SCHED_ROUND_ROBIN:
+		return &ConnectionProxies[CurrentConnectionProxy++ % ConnectionProxiesNumber];
+	  case SESSION_SCHED_RANDOM:
+		return &ConnectionProxies[random() % ConnectionProxiesNumber];
+	  case SESSION_SCHED_LOAD_BALANCING:
+		min_workload = GetConnectionProxyWorkload(0);
+		least_loaded_proxy = 0;
+		for (i = 1; i < ConnectionProxiesNumber; i++)
+		{
+			int workload = GetConnectionProxyWorkload(i);
+			if (workload < min_workload)
+			{
+				min_workload = workload;
+				least_loaded_proxy = i;
+			}
+		}
+		return &ConnectionProxies[least_loaded_proxy];
+	  default:
+		Assert(false);
+	}
+	return NULL;
+}
+
+
 /*
  * Main idle loop of postmaster
  *
@@ -1710,14 +1853,26 @@ ServerLoop(void)
 					port = ConnCreate(ListenSocket[i]);
 					if (port)
 					{
-						BackendStartup(port);
-
-						/*
-						 * We no longer need the open socket or port structure
-						 * in this process
-						 */
-						StreamClose(port->sock);
-						ConnFree(port);
+						if (ConnectionProxies && ListenPort[i] == ProxyPortNumber)
+						{
+							ConnectionProxy* proxy = SelectConnectionProxy();
+							if (pg_send_sock(proxy->socks[0], port->sock, proxy->pid) < 0)
+							{
+								elog(LOG, "could not send socket to connection pool: %m");
+							}
+							ConnFree(port);
+						}
+						else
+						{
+							BackendStartup(port, NULL);
+
+							/*
+							 * We no longer need the open socket or port structure
+							 * in this process
+							 */
+							StreamClose(port->sock);
+							ConnFree(port);
+						}
 					}
 				}
 			}
@@ -1789,6 +1944,8 @@ ServerLoop(void)
 		if (StartWorkerNeeded || HaveCrashedWorker)
 			maybe_start_bgworkers();
 
+		StartConnectionProxies();
+
 #ifdef HAVE_PTHREAD_IS_THREADED_NP
 
 		/*
@@ -1905,8 +2062,6 @@ ProcessStartupPacket(Port *port, bool SSLdone)
 {
 	int32		len;
 	void	   *buf;
-	ProtocolVersion proto;
-	MemoryContext oldcontext;
 
 	pq_startmsgread();
 	if (pq_getbytes((char *) &len, 4) == EOF)
@@ -1955,6 +2110,15 @@ ProcessStartupPacket(Port *port, bool SSLdone)
 	}
 	pq_endmsgread();
 
+	return ParseStartupPacket(port, TopMemoryContext, buf, len, SSLdone);
+}
+
+int
+ParseStartupPacket(Port *port, MemoryContext memctx, void* buf, int len, bool SSLdone)
+{
+	ProtocolVersion proto;
+	MemoryContext oldcontext;
+
 	/*
 	 * The first field is either a protocol version number or a special
 	 * request code.
@@ -2029,7 +2193,7 @@ retry1:
 	 * not worry about leaking this storage on failure, since we aren't in the
 	 * postmaster process anymore.
 	 */
-	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
+	oldcontext = MemoryContextSwitchTo(memctx);
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2694,6 +2858,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
+				StopConnectionProxies(SIGTERM);
+
 				/*
 				 * If we're in recovery, we can't kill the startup process
 				 * right away, because at present doing so does not release
@@ -2771,6 +2937,9 @@ pmdie(SIGNAL_ARGS)
 				/* and the walwriter too */
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
+
+				StopConnectionProxies(SIGTERM);
+
 				pmState = PM_WAIT_BACKENDS;
 			}
 
@@ -4000,6 +4169,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4009,8 +4179,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4114,6 +4284,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4810,6 +4982,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -4950,6 +5123,19 @@ SubPostmasterMain(int argc, char *argv[])
 
 		AutoVacWorkerMain(argc - 2, argv + 2);	/* does not return */
 	}
+	if (strcmp(argv[1], "--forkproxy") == 0)
+	{
+		/* Restore basic shared memory pointers */
+		InitShmemAccess(UsedShmemSegAddr);
+
+		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
+		InitProcess();
+
+		/* Attach process to shared data structures */
+		CreateSharedMemoryAndSemaphores(false, 0);
+
+		ConnectionProxyMain(argc - 2, argv + 2);	/* does not return */
+	}
 	if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
 	{
 		int			shmem_slot;
@@ -5018,7 +5204,6 @@ ExitPostmaster(int status)
 				 errmsg_internal("postmaster became multithreaded"),
 				 errdetail("Please report this to <[email-masked]>.")));
 #endif
-
 	/* should cleanup shared memory and kill all backends */
 
 	/*
@@ -5507,6 +5692,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
+ *		Start an proxy worker process.
+ *
+ * This function is here because it enters the resulting PID into the
+ * postmaster's private backends list.
+ *
+ * NB -- this code very roughly matches BackendStartup.
+ */
+static void
+StartProxyWorker(int id)
+{
+	Backend    *bn;
+	int         pid;
+
+	/*
+	 * Compute the cancel key that will be assigned to this session. We
+	 * probably don't need cancel keys for autovac workers, but we'd
+	 * better have something random in the field to prevent unfriendly
+	 * people from sending cancels to them.
+	 */
+	if (!RandomCancelKey(&MyCancelKey))
+	{
+		ereport(LOG,
+				(errcode(ERRCODE_INTERNAL_ERROR),
+				 errmsg("could not generate random cancel key")));
+		return   ;
+	}
+	bn = (Backend *) malloc(sizeof(Backend));
+	if (bn)
+	{
+		bn->cancel_key = MyCancelKey;
+
+		/* Autovac workers are not dead_end and need a child slot */
+		bn->dead_end = false;
+		bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
+		bn->bgworker_notify = false;
+
+		MyProxyId = id;
+		MyProxySocket = ConnectionProxies[id].socks[1];
+		pid = ConnectionProxyStart();
+		if (pid > 0)
+		{
+			bn->pid = pid;
+			bn->bkend_type = BACKEND_TYPE_BGWORKER;
+			dlist_push_head(&BackendList, &bn->elem);
+#ifdef EXEC_BACKEND
+			ShmemBackendArrayAdd(bn);
+#endif
+			/* all OK */
+			ConnectionProxies[id].pid = pid;
+			ProxyState[id].pid = pid;
+			return;
+		}
+
+		/*
+		 * fork failed, fall through to report -- actual error message was
+		 * logged by ConnectionProxyStart
+		 */
+		(void) ReleasePostmasterChildSlot(bn->child_slot);
+		free(bn);
+	}
+	else
+		ereport(LOG,
+				(errcode(ERRCODE_OUT_OF_MEMORY),
+				 errmsg("out of memory")));
+}
+
+/*
  * MaybeStartWalReceiver
  *		Start the WAL receiver process, if not running and our state allows.
  */
@@ -6084,6 +6337,10 @@ save_backend_variables(BackendParameters *param, Port *port,
 
 	strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
 
+	if (!write_inheritable_socket(&param->proxySocket, MyProxySocket, childPid))
+		return false;
+	param->proxyId = MyProxyId;
+
 	return true;
 }
 
@@ -6312,6 +6569,9 @@ restore_backend_variables(BackendParameters *param, Port *port)
 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
 
 	strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
+
+	read_inheritable_socket(&MyProxySock, &param->proxySocket);
+	MyProxyId = param->proxyId;
 }

diff --git a/src/backend/postmaster/proxy.c b/src/backend/postmaster/proxy.c
new file mode 100644
index 0000000..4265ebd
--- /dev/null
+++ b/src/backend/postmaster/proxy.c
@@ -0,0 +1,907 @@
+#include <unistd.h>
+#include <errno.h>
+
+#include "postgres.h"
+#include "funcapi.h"
+#include "miscadmin.h"
+#include "pgstat.h"
+#include "postmaster/postmaster.h"
+#include "postmaster/proxy.h"
+#include "postmaster/fork_process.h"
+#include "access/htup_details.h"
+#include "storage/ipc.h"
+#include "storage/latch.h"
+#include "storage/proc.h"
+#include "storage/procarray.h"
+#include "utils/builtins.h"
+#include "utils/memutils.h"
+#include "libpq/libpq.h"
+#include "libpq/libpq-be.h"
+#include "libpq/pqsignal.h"
+#include "tcop/tcopprot.h"
+#include "utils/timeout.h"
+#include "utils/ps_status.h"
+#include "../interfaces/libpq/libpq-fe.h"
+#include "../interfaces/libpq/libpq-int.h"
+
+#define INIT_BUF_SIZE      (64*1024)
+#define MAX_READY_EVENTS   128
+#define DB_HASH_SIZE       101
+#define PROXY_WAIT_TIMEOUT 1000 /* 1 second */
+
+struct SessionPool;
+struct Proxy;
+
+typedef struct
+{
+	char database[NAMEDATALEN];
+	char username[NAMEDATALEN];
+}
+SessionPoolKey;
+
+typedef struct Channel
+{
+	char*    buf;
+	int      rx_pos;
+	int      tx_pos;
+	int      tx_size;
+	int      buf_size;
+	int      event_pos;          /* Position of wait event returned by AddWaitEventToSet */
+
+	Port*    client_port;        /* Not null for client, null for server */
+
+	pgsocket backend_socket;
+	PGPROC*  backend_proc;
+	int      backend_pid;
+	bool     backend_is_tainted;
+	bool     backend_is_ready;   /* ready for query */
+	bool     is_interrupted;     /* client interrupts query execution */
+	bool     is_disconnected;
+
+	int      handshake_response_size;
+	char*    handshake_response;
+
+	struct Channel* peer;
+	struct Channel* next;
+	struct Proxy*   proxy;
+	struct SessionPool* pool;
+}
+Channel;
+
+typedef struct Proxy
+{
+	MemoryContext memctx;        /* Memory context for this proxy (used only in single thread) */
+	MemoryContext tmpctx;        /* Temporary memory context used for parsing startup packet */
+	WaitEventSet* wait_events;   /* Set of socket descriptors of backends and clients socket descriptors */
+	HTAB*    pools;              /* Session pool map with dbname/role used as a key */
+	int      n_accepted_connections; /* Number of accepted, but not yet established connections
+									  * (startup package is not received and db/role are not known) */
+	int      max_backends;       /* Maximal number of backends per database */
+	bool     shutdown;           /* Shutdown flag */
+	Channel* hangout;            /* List of disconncted backends */
+	ConnectionProxyState* state; /* State of proxy */
+} Proxy;
+
+typedef struct SessionPool
+{
+	SessionPoolKey key;
+	Channel* idle_backends;
+	Channel* pending_clients;
+	Proxy*   proxy;
+	int      n_launched_backends; /* Total number of launched backends */
+	int      n_idle_backends;     /* Number of backends in idle state */
+	int      n_connected_clients; /* Total number of connected clients */
+	int      n_idle_clients;      /* Number of clients in idle state */
+	int      n_pending_clients;   /* Number of clients waiting for free backend */
+}
+SessionPool;
+
+static void channel_remove(Channel* chan);
+static Channel* backend_start(SessionPool* pool, Port* client_port);
+static bool channel_read(Channel* chan);
+static bool channel_write(Channel* chan, bool synchronous);
+
+/*
+ * #define ELOG(severity, fmt,...) elog(severity, "PROXY: " fmt, ## __VA_ARGS__)
+ */
+#define ELOG(severity,fmt,...)
+
+static Proxy* proxy;
+int MyProxyId;
+pgsocket MyProxySocket;
+ConnectionProxyState* ProxyState;
+
+/**
+ * Backend is ready for next command outside transaction block (idle state).
+ * Now if backebd is not tainted it is possible to schedule some other client to this backend
+ */
+static bool
+backend_reschedule(Channel* chan)
+{
+	chan->backend_is_ready = false;
+	if (chan->backend_proc == NULL) /* Lazy resolving of PGPROC entry */
+	{
+		Assert(chan->backend_pid != 0);
+		chan->backend_proc = BackendPidGetProc(chan->backend_pid);
+		Assert(chan->backend_proc); /* If backend completes execution of some query, then it has definitely registered itself in procarray */
+	}
+	if (!chan->backend_proc->is_tainted) /* If backend is not storing some session context */
+	{
+		Channel* pending = chan->pool->pending_clients;
+		Assert(!chan->backend_is_tainted);
+		chan->peer->peer = NULL;
+		chan->pool->n_idle_clients += 1;
+		if (pending)
+		{
+            /* Has pending clients: serve one of them */
+			ELOG(LOG, "Backed %d is reassigned to client %p", chan->backend_pid, pending);
+			chan->pool->pending_clients = pending->next;
+			chan->peer = pending;
+			pending->peer = chan;
+			chan->pool->n_pending_clients -= 1;
+			if (pending->tx_size == 0) /* new client has sent startup packet and we now need to send handshake response */
+			{
+				Assert(chan->handshake_response != NULL); /* backend already send handshake response */
+				Assert(chan->handshake_response_size < chan->buf_size);
+				memcpy(chan->buf, chan->handshake_response, chan->handshake_response_size);
+				chan->rx_pos = chan->tx_size = chan->handshake_response_size;
+				ELOG(LOG, "Simulate response for startup packet to client %p", pending);
+				return channel_write(pending, false);
+			}
+			else
+			{
+				ELOG(LOG, "Try to send pending request from client %p to backend %p (pid %d)", pending, chan, chan->backend_pid);
+				Assert(pending->tx_pos == 0 && pending->rx_pos >= pending->tx_size);
+				return channel_write(chan, false); /* Send pending request to backend */
+			}
+		}
+		else /* return backend to the list of idle backends */
+		{
+			ELOG(LOG, "Backed %d is idle", chan->backend_pid);
+			chan->next = chan->pool->idle_backends;
+			chan->pool->idle_backends = chan;
+			chan->pool->n_idle_backends += 1;
+			chan->peer = NULL;
+		}
+	}
+	else if (!chan->backend_is_tainted) /* if it was not marked as tainted before... */
+	{
+		chan->backend_is_tainted = true;
+		chan->proxy->state->n_dedicated_backends += 1;
+	}
+	return true;
+}
+
+/**
+ * Parse client's startup packet and assign client to proper connection pool based on dbname/role
+ */
+static bool
+client_connect(Channel* chan, int startup_packet_size)
+{
+	bool found;
+	SessionPoolKey key;
+	char* startup_packet = chan->buf;
+
+	Assert(chan->client_port);
+
+	MemoryContextReset(chan->proxy->tmpctx);
+	MemoryContextSwitchTo(chan->proxy->tmpctx);
+	MyProcPort = chan->client_port;
+	pq_init();
+	if (ParseStartupPacket(chan->client_port, chan->proxy->tmpctx, startup_packet+4, startup_packet_size-4, false) != STATUS_OK) /* skip packet size */
+	{
+		elog(WARNING, "Failed to parse startup packet for client %p", chan);
+		return false;
+	}
+	chan->proxy->state->n_ssl_clients += chan->client_port->ssl_in_use;
+	pg_set_noblock(chan->client_port->sock);
+	memset(&key, 0, sizeof(key));
+	strlcpy(key.database, chan->client_port->database_name, NAMEDATALEN);
+	strlcpy(key.username, chan->client_port->user_name, NAMEDATALEN);
+
+	ELOG(LOG, "Client %p connects to %s/%s", chan, key.database, key.username);
+
+	chan->pool = (SessionPool*)hash_search(chan->proxy->pools, &key, HASH_ENTER, &found);
+	if (!found)
+	{
+		chan->proxy->state->n_pools += 1;
+		memset((char*)chan->pool + sizeof(SessionPoolKey), 0, sizeof(SessionPool) - sizeof(SessionPoolKey));
+	}
+	chan->pool->proxy = chan->proxy;
+	chan->pool->n_connected_clients += 1;
+	chan->pool->n_idle_clients += 1;
+	chan->proxy->n_accepted_connections -= 1;
+	return true;
+}
+
+/*
+ * Attach client to backend. Return true if new backend is attached, false otherwise.
+ */
+static bool
+client_attach(Channel* chan)
+{
+	Channel* idle_backend = chan->pool->idle_backends;
+	chan->pool->n_idle_clients -= 1;
+	if (idle_backend)
+	{
+		/* has idle backend */
+		Assert(!idle_backend->backend_is_tainted);
+		chan->peer = idle_backend;
+		idle_backend->peer = chan;
+		chan->pool->idle_backends = idle_backend->next;
+		chan->pool->n_idle_backends -= 1;
+		ELOG(LOG, "Attach client %p to backend %p (pid %d)", chan, idle_backend, idle_backend->backend_pid);
+	}
+	else /* all backends are busy */
+	{
+		if (chan->pool->n_launched_backends < chan->proxy->max_backends)
+		{
+			/* Try to start new backend */
+			idle_backend = backend_start(chan->pool, chan->client_port);
+			if (idle_backend != NULL)
+			{
+				ELOG(LOG, "Start new backend %p (pid %d) for client %p",
+					 idle_backend, idle_backend->backend_pid, chan);
+				chan->peer = idle_backend;
+				idle_backend->peer = chan;
+				return true;
+			}
+		}
+		/* Wait until some backend is available */
+		ELOG(LOG, "Client %p is waiting for available backends", chan);
+		chan->next = chan->pool->pending_clients;
+		chan->pool->pending_clients = chan;
+		chan->pool->n_pending_clients += 1;
+	}
+	return false;
+}
+
+/*
+ * Handle communication failure for this channel.
+ * It is not possible to remove channel immediately because it can be triggered by other epoll events.
+ * So link all channels in L1 list for pending delete.
+ */
+static void
+channel_hangout(Channel* chan, char const* op)
+{
+	Channel* peer = chan->peer;
+	if (chan->is_disconnected)
+	   return;
+
+	if (chan->client_port) {
+		ELOG(LOG, "Hangout client %p due to %s error: %m", chan, op);
+	} else {
+		ELOG(LOG, "Hangout backend %p (pid %d) due to %s error: %m", chan, chan->backend_pid, op);
+	}
+	chan->next = chan->proxy->hangout;
+	chan->proxy->hangout = chan;
+	chan->is_disconnected = true;
+	chan->backend_is_ready = false;
+	chan->peer = NULL;
+	if (chan->client_port && peer)
+	{
+		if (!chan->is_interrupted) /* Client didn't sent 'X' command, so do it for him */
+		{
+			peer->is_interrupted = true;
+			channel_write(peer, false);
+		}
+		else
+		{
+			backend_reschedule(peer);
+		}
+	}
+}
+
+/*
+ * Try to write data to the socket.
+ */
+static ssize_t
+socket_write(Channel* chan, char const* buf, size_t size)
+{
+	ssize_t rc;
+#ifdef USE_SSL
+	int waitfor = 0;
+	if (chan->client_port && chan->client_port->ssl_in_use)
+		rc = be_tls_write(chan->client_port, buf, size, &waitfor);
+	else
+#endif
+		rc = chan->client_port
+			? secure_raw_write(chan->client_port, buf, size)
+			: write(chan->backend_socket, buf, size);
+	if (rc == 0 || (rc < 0 && (errno != EAGAIN && errno != EWOULDBLOCK)))
+	{
+		channel_hangout(chan, "write");
+	}
+	return rc;
+}
+
+
+/*
+ * Try to send some data to the channel.
+ * Data is located in peer buffer. Because of using edge-triggered mode we have have to use non-blocking IO
+ * and try to write all avaialble data. Once write is completed we should try to read more data from source socket.
+ * "sycnhronous" flag is used to avoid infinite recursion or reads-writers.
+ * Returns true if there is nothing to do or operation is succeffully completed, false in case of error
+ * or socket buffer is full.
+ */
+static bool
+channel_write(Channel* chan, bool synchronous)
+{
+	Channel* peer = chan->peer;
+	if (!chan->client_port && chan->is_interrupted)
+	{
+		char const terminate[] = {'X', 0, 0, 0, 4};
+		if (socket_write(chan, terminate, sizeof(terminate)) <= 0)
+			return false;
+		/* detach backend from client */
+		chan->is_interrupted = false;
+		backend_reschedule(chan);
+		return true;
+	}
+	if (peer == NULL)
+		return false;
+
+	while (peer->tx_pos < peer->tx_size) /* has something to write */
+	{
+		ssize_t rc = socket_write(chan, peer->buf + peer->tx_pos, peer->tx_size - peer->tx_pos);
+		ELOG(LOG, "%p: write %d tx_pos=%d, tx_size=%d: %m", chan, (int)rc, peer->tx_pos, peer->tx_size);
+		if (rc <= 0)
+			return false;
+		if (chan->client_port)
+			chan->proxy->state->tx_bytes += rc;
+		else
+			chan->proxy->state->rx_bytes += rc;
+		peer->tx_pos += rc;
+	}
+	if (peer->tx_size != 0)
+	{
+		chan->backend_is_ready = false;
+		Assert(peer->rx_pos >= peer->tx_size);
+		memmove(peer->buf, peer->buf + peer->tx_size, peer->rx_pos - peer->tx_size);
+		peer->rx_pos -= peer->tx_size;
+		peer->tx_pos = peer->tx_size = 0;
+	}
+	return synchronous || channel_read(peer); /* write is not invoked from read */
+}
+
+/*
+ * Try to read more data from the channel and send it to the peer.
+ */
+static bool
+channel_read(Channel* chan)
+{
+	int  msg_start;
+	while (chan->tx_size == 0) /* there is no pending write op */
+	{
+		ssize_t rc;
+#ifdef USE_SSL
+		int waitfor = 0;
+		if (chan->client_port && chan->client_port->ssl_in_use)
+			rc = be_tls_read(chan->client_port, chan->buf + chan->rx_pos, chan->buf_size - chan->rx_pos, &waitfor);
+		else
+#endif
+			rc = chan->client_port
+				? secure_raw_read(chan->client_port, chan->buf + chan->rx_pos, chan->buf_size - chan->rx_pos)
+				: read(chan->backend_socket, chan->buf + chan->rx_pos, chan->buf_size - chan->rx_pos);
+
+		ELOG(LOG, "%p: read %d: %m", chan, (int)rc);
+		if (rc <= 0)
+		{
+			if (rc == 0 || (errno != EAGAIN && errno != EWOULDBLOCK))
+				channel_hangout(chan, "read");
+			return false; /* wait for more data */
+		}
+		chan->rx_pos += rc;
+		msg_start = 0;
+		while (chan->rx_pos - msg_start >= 5) /* have message code + length */
+		{
+			int msg_len;
+			bool handshake = false;
+			if (chan->pool == NULL) /* process startup packet */
+			{
+				Assert(msg_start == 0);
+				memcpy(&msg_len, chan->buf + msg_start, sizeof(msg_len));
+				msg_len = ntohl(msg_len);
+				handshake = true;
+			}
+			else
+			{
+				ELOG(LOG, "%p receive message %c", chan, chan->buf[msg_start]); 
+				memcpy(&msg_len, chan->buf + msg_start + 1, sizeof(msg_len));
+				msg_len = ntohl(msg_len) + 1;
+			}
+			if (msg_start + msg_len > chan->buf_size)
+			{
+				chan->buf_size = msg_start + msg_len;
+				chan->buf = realloc(chan->buf, chan->buf_size);
+			}
+			if (chan->rx_pos - msg_start >= msg_len) /* Message is completely fetched */
+			{
+				int response_size = msg_start + msg_len;
+				if (chan->pool == NULL) /* receive startup packet */
+				{
+					Assert(chan->client_port);
+					if (!client_connect(chan, msg_len))
+					{
+						chan->is_disconnected = true;
+						channel_remove(chan);
+						return false;
+					}
+				}
+				else if (!chan->client_port /* message from backend */
+					&& chan->buf[msg_start] == 'Z'  /* ready for query */
+					&& chan->buf[msg_start+5] == 'I') /* Transaction block status is idle */
+				{
+					Assert(chan->rx_pos - msg_start == msg_len); /* should be last message */
+					chan->backend_is_ready = true;
+					chan->proxy->state->n_transactions += 1;
+				}
+				else if (chan->client_port /* message from client */
+						 && chan->buf[msg_start] == 'X')	/* terminate message */
+				{
+					chan->is_interrupted = true;
+					if (chan->peer == NULL || !chan->peer->backend_is_tainted)
+					{
+						/* Skip terminate message to idle and non-tainted backends */
+						channel_hangout(chan, "terminate");
+						return false;
+					}
+				}
+				if (chan->peer == NULL)  /* client is not yet connected to backend */
+				{
+					if (!chan->client_port)
+					{
+						/* We are not expecting messages from idle backend. Assume that it some error or shutdown. */
+						channel_hangout(chan, "idle");
+						return false;
+					}
+					client_attach(chan);
+					if (handshake) /* send handshake response to the client */
+					{
+                        /* If we attach new client to existed backend, then we need to send handshake response to the client */
+						Channel* backend = chan->peer;
+						Assert(chan->rx_pos == msg_len && msg_start == 0);
+						chan->rx_pos = 0; /* skip startup packet */
+						if (backend != NULL) /* if backend was assigned */
+						{
+							Assert(backend->handshake_response != NULL); /* backend already sends handshake response */
+							Assert(backend->handshake_response_size < backend->buf_size);
+							memcpy(backend->buf, backend->handshake_response, backend->handshake_response_size);
+							backend->rx_pos = backend->tx_size = backend->handshake_response_size;
+							return channel_write(chan, false);
+						}
+						else
+						{
+							/* Handshake response will be send to client later when backen is assigned */
+							return false;
+						}
+					}
+					else if (chan->peer == NULL) /* backend was not assigned */
+					{
+						chan->tx_size = response_size; /* query will be send later once backend is assigned */
+						return false;
+					}
+				}
+				msg_start += msg_len;
+			}
+			else break;
+		}
+		if (msg_start != 0)
+		{
+			/* has some complete messages to send to peer */
+			Assert(chan->tx_pos == 0);
+			Assert(chan->rx_pos >= msg_start);
+			chan->tx_size = msg_start;
+			if (!channel_write(chan->peer, true))
+				return false;
+		}
+		if (chan->backend_is_ready)
+			return backend_reschedule(chan);
+	}
+	return true;
+}
+
+static Channel*
+channel_create(Proxy* proxy)
+{
+	Channel* chan = (Channel*)calloc(1, sizeof(Channel));
+	chan->proxy = proxy;
+	chan->buf = malloc(INIT_BUF_SIZE);
+	chan->buf_size = INIT_BUF_SIZE;
+	chan->tx_pos = chan->rx_pos = chan->tx_size = 0;
+	return chan;
+}
+
+static bool
+channel_register(Proxy* proxy, Channel* chan)
+{
+	pgsocket sock = chan->client_port ? chan->client_port->sock : chan->backend_socket;
+	pg_set_noblock(sock);
+	chan->event_pos =
+		AddWaitEventToSet(proxy->wait_events, WL_SOCKET_READABLE|WL_SOCKET_WRITEABLE|WL_SOCKET_EDGE,
+						  sock, NULL, chan);
+	if (chan->event_pos < 0)
+	{
+		elog(WARNING, "PROXY: Failed to add new client - too much sessions: %d clients, %d backends. "
+					 "Try to increase 'max_sessions' configuration parameter.",
+					 proxy->state->n_clients, proxy->state->n_backends);
+		return false;
+	}
+	return true;
+}
+
+/*
+ * Start new backend for particular pool associated with dbname/role combination.
+ * Backend is forked using BackendStartup function.
+ * This function is called from proxy thread and access static variabls of backend.c,
+ * so use mutex to prevent race condition.
+ */
+static Channel*
+backend_start(SessionPool* pool, Port* client_port)
+{
+	Channel* chan;
+	char postmaster_port[8];
+	char const* keywords[] = {"host","port","dbname","user","sslmode","application_name",NULL};
+	char const* values[] = {"localhost",postmaster_port,pool->key.database, pool->key.username,"disable","pool_worker",NULL};
+	PGconn* conn;
+	char* msg;
+	int int32_buf;
+	int msg_len;
+	static bool libpqconn_loaded;
+
+	if (!libpqconn_loaded)
+	{
+		load_file("libpqconn", false);
+		libpqconn_loaded = true;
+	}
+	pg_itoa(PostPortNumber, postmaster_port);
+	conn = LibpqConnectdbParams(keywords, values);
+	if (!conn)
+		return NULL;
+
+	chan = channel_create(pool->proxy);
+	chan->pool = pool;
+	chan->backend_socket = conn->sock;
+	pg_set_noblock(conn->sock);
+
+	/* Save handshake response */
+	chan->handshake_response_size = conn->inEnd;
+	chan->handshake_response = malloc(chan->handshake_response_size);
+	memcpy(chan->handshake_response, conn->inBuffer, chan->handshake_response_size);
+
+	/* Extract backend pid */
+	msg = chan->handshake_response;
+	while (*msg != 'K')
+	{
+		memcpy(&int32_buf, ++msg, sizeof(int32_buf));
+		msg_len = ntohl(int32_buf);
+		msg += msg_len;
+		Assert(msg < chan->handshake_response + chan->handshake_response_size);
+	}
+	memcpy(&int32_buf, msg+5, sizeof(int32_buf));
+	chan->backend_pid = ntohl(int32_buf);
+
+	if (channel_register(pool->proxy, chan))
+	{
+		pool->proxy->state->n_backends += 1;
+		pool->n_launched_backends += 1;
+	}
+	else
+	{
+		free(chan->buf);
+		free(chan);
+		close(chan->backend_socket);
+		chan = NULL;
+	}
+	return chan;
+}
+
+/*
+ * Add new client, accepted by postmaster. This client will be assigned to concrete session pool
+ * when it's startup packet is received.
+ */
+static void
+proxy_add_client(Proxy* proxy, Port* port)
+{
+	Channel* chan = channel_create(proxy);
+	chan->client_port = port;
+	chan->backend_socket = PGINVALID_SOCKET;
+	if (channel_register(proxy, chan)) {
+		ELOG(LOG, "Add new client %p", chan);
+		proxy->n_accepted_connections += 1;
+		proxy->state->n_clients += 1;
+	}
+}
+
+/*
+ * Perform delayed deletion of channel
+ */
+static void
+channel_remove(Channel* chan)
+{
+	Assert(chan->is_disconnected); /* should be marked as disconnected by channel_hangout */
+	DeleteWaitEventFromSet(chan->proxy->wait_events, chan->event_pos);
+	if (chan->client_port)
+	{
+		if (chan->pool)
+			chan->pool->n_connected_clients -= 1;
+		else
+			chan->proxy->n_accepted_connections -= 1;
+		chan->proxy->state->n_clients -= 1;
+		chan->proxy->state->n_ssl_clients -= chan->client_port->ssl_in_use;
+		close(chan->client_port->sock);
+		free(chan->client_port);
+	}
+	else
+	{
+		chan->proxy->state->n_backends -= 1;
+		chan->proxy->state->n_dedicated_backends -= chan->backend_is_tainted;
+		chan->pool->n_launched_backends -= 1;
+		close(chan->backend_socket);
+		free(chan->handshake_response);
+	}
+	free(chan->buf);
+	free(chan);
+}
+
+/*
+ * Create new proxy.
+ */
+static Proxy*
+proxy_create(pgsocket postmaster_socket, ConnectionProxyState* state, int max_backends)
+{
+	HASHCTL ctl;
+	Proxy*  proxy = calloc(1, sizeof(Proxy));
+	proxy->memctx = AllocSetContextCreate(TopMemoryContext,
+										  "Proxy",
+										  ALLOCSET_DEFAULT_SIZES);
+	proxy->tmpctx = AllocSetContextCreate(proxy->memctx,
+										  "Startup packet parsing context",
+										  ALLOCSET_DEFAULT_SIZES);
+	MemSet(&ctl, 0, sizeof(ctl));
+	ctl.keysize = sizeof(SessionPoolKey);
+	ctl.entrysize = sizeof(SessionPool);
+	ctl.hcxt = proxy->memctx;
+	proxy->pools = hash_create("Pool by database and user", DB_HASH_SIZE,
+							   &ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
+	proxy->wait_events = CreateWaitEventSet(TopMemoryContext, MaxSessions*2); /* we need events both for clients and backends */
+	AddWaitEventToSet(proxy->wait_events, WL_SOCKET_READABLE,
+					  postmaster_socket, NULL, NULL);
+	proxy->max_backends = max_backends;
+	proxy->state = state;
+	return proxy;
+}
+
+/*
+ * Main proxy loop
+ */
+static void
+proxy_loop(Proxy* proxy)
+{
+	int i, n_ready;
+	WaitEvent ready[MAX_READY_EVENTS];
+	Channel *chan, *next;
+
+	while (!proxy->shutdown)
+	{
+		/* Use timeout to allow normal proxy shutdown */
+		n_ready = WaitEventSetWait(proxy->wait_events, PROXY_WAIT_TIMEOUT, ready, MAX_READY_EVENTS, PG_WAIT_CLIENT);
+		for (i = 0; i < n_ready; i++) {
+			chan = (Channel*)ready[i].user_data;
+			if (chan == NULL) /* new connection from postmaster */
+			{
+				Port* port = (Port*)calloc(1, sizeof(Port));
+				port->sock = pg_recv_sock(ready[i].fd);
+			    if (port->sock == PGINVALID_SOCKET)
+					elog(ERROR, "Failed to receive session socket: %m");
+				proxy_add_client(proxy, port);
+			}
+			else
+			{
+				if (ready[i].events & WL_SOCKET_WRITEABLE) {
+					ELOG(LOG, "Channel %p is writable", chan);
+					channel_write(chan, false);
+				}
+				if (ready[i].events & WL_SOCKET_READABLE) {
+					ELOG(LOG, "Channel %p is readable", chan);
+					channel_read(chan);
+				}
+			}
+		}
+		/* Delayed deallocation of disconnected channels */
+		for (chan = proxy->hangout; chan != NULL; chan = next)
+		{
+			next = chan->next;
+			channel_remove(chan);
+		}
+		proxy->hangout = NULL;
+	}
+}
+
+
+static void
+proxy_handle_sigterm(SIGNAL_ARGS)
+{
+	if (proxy)
+		proxy->shutdown = true;
+}
+
+#ifdef EXEC_BACKEND
+static pid_t
+proxy_forkexec(void)
+{
+	char	   *av[10];
+	int			ac = 0;
+
+	av[ac++] = "postgres";
+	av[ac++] = "--forkproxy";
+	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
+	av[ac] = NULL;
+
+	Assert(ac < lengthof(av));
+
+	return postmaster_forkexec(ac, av);
+}
+#endif
+
+NON_EXEC_STATIC void
+ConnectionProxyMain(int argc, char *argv[])
+{
+	sigjmp_buf	local_sigjmp_buf;
+
+	/* Identify myself via ps */
+	init_ps_display("connection proxy", "", "", "");
+
+	SetProcessingMode(InitProcessing);
+
+	pqsignal(SIGTERM, proxy_handle_sigterm);
+	pqsignal(SIGQUIT, quickdie);
+	InitializeTimeouts();		/* establishes SIGALRM handler */
+
+	/* Early initialization */
+	BaseInit();
+
+	/*
+	 * Create a per-backend PGPROC struct in shared memory, except in the
+	 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
+	 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
+	 * had to do some stuff with LWLocks).
+	 */
+#ifndef EXEC_BACKEND
+	InitProcess();
+#endif
+
+	/*
+	 * If an exception is encountered, processing resumes here.
+	 *
+	 * See notes in postgres.c about the design of this coding.
+	 */
+	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
+	{
+		/* Prevents interrupts while cleaning up */
+		HOLD_INTERRUPTS();
+
+		/* Report the error to the server log */
+		EmitErrorReport();
+
+		/*
+		 * We can now go away.  Note that because we called InitProcess, a
+		 * callback was registered to do ProcKill, which will clean up
+		 * necessary state.
+		 */
+		proc_exit(0);
+	}
+	/* We can now handle ereport(ERROR) */
+	PG_exception_stack = &local_sigjmp_buf;
+
+	PG_SETMASK(&UnBlockSig);
+
+	proxy = proxy_create(MyProxySocket, &ProxyState[MyProxyId], SessionPoolSize);
+	proxy_loop(proxy);
+
+	proc_exit(0);
+}
+
+int
+ConnectionProxyStart()
+{
+	pid_t		worker_pid;
+
+#ifdef EXEC_BACKEND
+	switch ((worker_pid = proxy_forkexec()))
+#else
+	switch ((worker_pid = fork_process()))
+#endif
+	{
+		case -1:
+			ereport(LOG,
+					(errmsg("could not fork proxy worker process: %m")));
+			return 0;
+
+#ifndef EXEC_BACKEND
+		case 0:
+			/* in postmaster child ... */
+			InitPostmasterChild();
+
+			ConnectionProxyMain(0, NULL);
+			break;
+#endif
+		default:
+		  elog(LOG, "Start proxy process %d", (int) worker_pid);
+		  return (int) worker_pid;
+	}
+
+	/* shouldn't get here */
+	return 0;
+}
+
+int ConnectionProxyShmemSize(void)
+{
+	return ConnectionProxiesNumber*sizeof(ConnectionProxyState);
+}
+
+void ConnectionProxyShmemInit(void)
+{
+	bool found;
+	ProxyState = (ConnectionProxyState*)ShmemInitStruct("connection proxy contexts",
+															 ConnectionProxyShmemSize(), &found);
+	if (!found)
+		memset(ProxyState, 0, ConnectionProxyShmemSize());
+}
+
+PG_FUNCTION_INFO_V1(pg_pooler_state);
+
+typedef struct
+{
+	int proxy_id;
+	TupleDesc ret_desc;
+} PoolerStateContext;
+
+/**
+ * Return information about proxy state
+ */
+Datum pg_pooler_state(PG_FUNCTION_ARGS)
+{
+    FuncCallContext* srf_ctx;
+	MemoryContext old_context;
+	PoolerStateContext* ps_ctx;
+	HeapTuple tuple;
+	Datum values[9];
+	bool  nulls[9];
+	int id;
+	int i;
+
+	if (SRF_IS_FIRSTCALL())
+	{
+		srf_ctx = SRF_FIRSTCALL_INIT();
+		old_context = MemoryContextSwitchTo(srf_ctx->multi_call_memory_ctx);
+        ps_ctx = (PoolerStateContext*)palloc(sizeof(PoolerStateContext));
+        get_call_result_type(fcinfo, NULL, &ps_ctx->ret_desc);
+		ps_ctx->proxy_id = 0;
+		srf_ctx->user_fctx = ps_ctx;
+		MemoryContextSwitchTo(old_context);
+	}
+	srf_ctx = SRF_PERCALL_SETUP();
+	ps_ctx = srf_ctx->user_fctx;
+	id = ps_ctx->proxy_id;
+	if (id == ConnectionProxiesNumber)
+		SRF_RETURN_DONE(srf_ctx);
+
+	values[0] = Int32GetDatum(ProxyState[id].pid);
+	values[1] = Int32GetDatum(ProxyState[id].n_clients);
+	values[2] = Int32GetDatum(ProxyState[id].n_ssl_clients);
+	values[3] = Int32GetDatum(ProxyState[id].n_pools);
+	values[4] = Int32GetDatum(ProxyState[id].n_backends);
+	values[5] = Int32GetDatum(ProxyState[id].n_dedicated_backends);
+	values[6] = Int64GetDatum(ProxyState[id].tx_bytes);
+	values[7] = Int64GetDatum(ProxyState[id].rx_bytes);
+	values[8] = Int64GetDatum(ProxyState[id].n_transactions);
+
+	for (i = 0; i <= 8; i++)
+		nulls[i] = false;
+
+	ps_ctx->proxy_id += 1;
+	tuple = heap_form_tuple(ps_ctx->ret_desc, values, nulls);
+	SRF_RETURN_NEXT(srf_ctx, HeapTupleGetDatum(tuple));
+}
+
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 0c86a58..bcbde42 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -28,6 +28,7 @@
 #include "postmaster/bgworker_internals.h"
 #include "postmaster/bgwriter.h"
 #include "postmaster/postmaster.h"
+#include "postmaster/proxy.h"
 #include "replication/logicallauncher.h"
 #include "replication/slot.h"
 #include "replication/walreceiver.h"
@@ -153,6 +154,7 @@ CreateSharedMemoryAndSemaphores(bool makePrivate, int port)
 #ifdef EXEC_BACKEND
 		size = add_size(size, ShmemBackendArraySize());
 #endif
+		size = add_size(size, ConnectionProxyShmemSize());
 
 		/* freeze the addin request size and include it */
 		addin_request_allowed = false;
@@ -261,6 +263,7 @@ CreateSharedMemoryAndSemaphores(bool makePrivate, int port)
 	WalSndShmemInit();
 	WalRcvShmemInit();
 	ApplyLauncherShmemInit();
+	ConnectionProxyShmemInit();
 
 	/*
 	 * Set up other modules that need some shared memory space
diff --git a/src/backend/storage/ipc/latch.c b/src/backend/storage/ipc/latch.c
index b080453..dd1cb73 100644
--- a/src/backend/storage/ipc/latch.c
+++ b/src/backend/storage/ipc/latch.c
@@ -77,6 +77,7 @@ struct WaitEventSet
 {
 	int			nevents;		/* number of registered events */
 	int			nevents_space;	/* maximum number of events in this set */
+	int         free_events;    /* L1-list of free events linked by "pos" and terminated by -1*/
 
 	/*
 	 * Array, of nevents_space length, storing the definition of events this
@@ -137,9 +138,9 @@ static void drainSelfPipe(void);
 #if defined(WAIT_USE_EPOLL)
 static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action);
 #elif defined(WAIT_USE_POLL)
-static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event, bool remove);
 #elif defined(WAIT_USE_WIN32)
-static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event, bool remove);
 #endif
 
 static inline int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
@@ -585,6 +586,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 	set->latch = NULL;
 	set->nevents_space = nevents;
 	set->exit_on_postmaster_death = false;
+	set->free_events = -1;
 
 #if defined(WAIT_USE_EPOLL)
 #ifdef EPOLL_CLOEXEC
@@ -691,9 +693,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
-	Assert(set->nevents < set->nevents_space);
+	if (set->nevents == set->nevents_space)
+		return -1;
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -720,8 +724,19 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
-	event = &set->events[set->nevents];
-	event->pos = set->nevents++;
+	free_event = set->free_events;
+	if (free_event >= 0)
+	{
+		event = &set->events[free_event];
+		set->free_events = event->pos;
+		event->pos = free_event;
+	}
+	else
+	{
+		event = &set->events[set->nevents];
+		event->pos = set->nevents;
+	}
+	set->nevents += 1;
 	event->fd = fd;
 	event->events = events;
 	event->user_data = user_data;
@@ -748,15 +763,30 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 #if defined(WAIT_USE_EPOLL)
 	WaitEventAdjustEpoll(set, event, EPOLL_CTL_ADD);
 #elif defined(WAIT_USE_POLL)
-	WaitEventAdjustPoll(set, event);
+	WaitEventAdjustPoll(set, event, false);
 #elif defined(WAIT_USE_WIN32)
-	WaitEventAdjustWin32(set, event);
+	WaitEventAdjustWin32(set, event, false);
 #endif
 
 	return event->pos;
 }
 
 /*
+ * Remove event with specified socket descriptor
+ */
+void DeleteWaitEventFromSet(WaitEventSet *set, int event_pos)
+{
+	WaitEvent  *event = &set->events[event_pos];
+#if defined(WAIT_USE_EPOLL)
+	WaitEventAdjustEpoll(set, event, EPOLL_CTL_DEL);
+#elif defined(WAIT_USE_POLL)
+	WaitEventAdjustPoll(set, event, true);
+#elif defined(WAIT_USE_WIN32)
+	WaitEventAdjustWin32(set, event, true);
+#endif
+}
+
+/*
  * Change the event mask and, in the WL_LATCH_SET case, the latch associated
  * with the WaitEvent.
  *
@@ -767,7 +797,7 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 {
 	WaitEvent  *event;
 
-	Assert(pos < set->nevents);
+	Assert(pos < set->nevents_space);
 
 	event = &set->events[pos];
 
@@ -804,9 +834,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 #if defined(WAIT_USE_EPOLL)
 	WaitEventAdjustEpoll(set, event, EPOLL_CTL_MOD);
 #elif defined(WAIT_USE_POLL)
-	WaitEventAdjustPoll(set, event);
+	WaitEventAdjustPoll(set, event, false);
 #elif defined(WAIT_USE_WIN32)
-	WaitEventAdjustWin32(set, event);
+	WaitEventAdjustWin32(set, event, false);
 #endif
 }
 
@@ -844,6 +874,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 			epoll_ev.events |= EPOLLIN;
 		if (event->events & WL_SOCKET_WRITEABLE)
 			epoll_ev.events |= EPOLLOUT;
+		if (event->events & WL_SOCKET_EDGE)
+			epoll_ev.events |= EPOLLET;
 	}
 
 	/*
@@ -852,19 +884,37 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
 				 errmsg("epoll_ctl() failed: %m")));
+
+	if (action == EPOLL_CTL_DEL)
+	{
+		int pos = event->pos;
+		event->fd = PGINVALID_SOCKET;
+		set->nevents -= 1;
+		event->pos = set->free_events;
+		set->free_events = pos;
+	}
 }
 #endif
 
 #if defined(WAIT_USE_POLL)
 static void
-WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event, bool remove)
 {
-	struct pollfd *pollfd = &set->pollfds[event->pos];
+	int pos = event->pos;
+	struct pollfd *pollfd = &set->pollfds[pos];
+
+	if (remove)
+	{
+		set->nevents -= 1;
+		*pollfd = set->pollfds[set->nevents];
+		set->events[pos] = set->events[set->nevents];
+		event->pos = pos;
+		return;
+	}
 
 	pollfd->revents = 0;
 	pollfd->fd = event->fd;
@@ -895,9 +945,25 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
 
 #if defined(WAIT_USE_WIN32)
 static void
-WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event, bool remove)
 {
-	HANDLE	   *handle = &set->handles[event->pos + 1];
+	int pos = event->pos;
+	HANDLE	   *handle = &set->handles[pos + 1];
+
+	if (remove)
+	{
+		Assert(event->fd != PGINVALID_SOCKET);
+
+		if (*handle != WSA_INVALID_EVENT)
+			WSACloseEvent(*handle);
+
+		set->nevents -= 1;
+		set->events[pos] = set->events[set->nevents];
+		*handle = set->handles[set->nevents + 1];
+		set->handles[set->nevents + 1] = WSA_INVALID_EVENT;
+		event->pos = pos;
+		return;
+	}
 
 	if (event->events == WL_LATCH_SET)
 	{
@@ -910,7 +976,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
 		if (event->events & WL_SOCKET_READABLE)
 			flags |= FD_READ;
@@ -927,8 +993,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 					 WSAGetLastError());
 		}
 		if (WSAEventSelect(event->fd, *handle, flags) != 0)
-			elog(ERROR, "failed to set up event for socket: error code %u",
-				 WSAGetLastError());
+			elog(ERROR, "failed to set up event for socket %p: error code %u",
+				 event->fd, WSAGetLastError());
 
 		Assert(event->fd != PGINVALID_SOCKET);
 	}
@@ -1330,7 +1396,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 	{
 		if (cur_event->reset)
 		{
-			WaitEventAdjustWin32(set, cur_event);
+			WaitEventAdjustWin32(set, cur_event, false);
 			cur_event->reset = false;
 		}
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 5ab7d3c..53ade20 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -4224,6 +4224,8 @@ PostgresMain(int argc, char *argv[],
 		 */
 		if (ConfigReloadPending)
 		{
+			if (RestartPoolerOnReload && strcmp(application_name, "pool_worker") == 0)
+				proc_exit(0);
 			ConfigReloadPending = false;
 			ProcessConfigFile(PGC_SIGHUP);
 		}
diff --git a/src/backend/utils/adt/lockfuncs.c b/src/backend/utils/adt/lockfuncs.c
index 525decb..e53b2d1 100644
--- a/src/backend/utils/adt/lockfuncs.c
+++ b/src/backend/utils/adt/lockfuncs.c
@@ -18,6 +18,7 @@
 #include "funcapi.h"
 #include "miscadmin.h"
 #include "storage/predicate_internals.h"
+#include "storage/proc.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
 
@@ -658,6 +659,7 @@ pg_isolation_test_session_is_blocked(PG_FUNCTION_ARGS)
 static void
 PreventAdvisoryLocksInParallelMode(void)
 {
+	MyProc->is_tainted = true;
 	if (IsInParallelMode())
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index c693977..49f31a7 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -130,9 +130,14 @@ int			max_parallel_maintenance_workers = 2;
  */
 int			NBuffers = 1000;
 int			MaxConnections = 90;
+int			SessionPoolSize = 0;
+int			ConnectionProxiesNumber = 1;
+int			SessionSchedule = SESSION_SCHED_ROUND_ROBIN;
+
 int			max_worker_processes = 8;
 int			max_parallel_workers = 8;
 int			MaxBackends = 0;
+int			MaxSessions = 1000;
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 10;
@@ -148,3 +153,4 @@ int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
 
 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 6fe1939..d88a4dd 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -451,6 +451,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
+static const struct config_enum_entry session_schedule_options[] = {
+	{"round-robin", SESSION_SCHED_ROUND_ROBIN, false},
+	{"random", SESSION_SCHED_RANDOM, false},
+	{"load-balancing", SESSION_SCHED_LOAD_BALANCING, false},
+	{NULL, 0, false}
+};
+
+
 /*
  * Options for enum values stored in other modules
  */
@@ -1226,6 +1234,16 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
+		{"restart_pooler_on_reload", PGC_SIGHUP, CONN_POOLING,
+		 gettext_noop("Restart session pool workers on pg_reload_conf()."),
+		 NULL,
+		},
+		&RestartPoolerOnReload,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
 		{"log_duration", PGC_SUSET, LOGGING_WHAT,
 			gettext_noop("Logs the duration of each completed SQL statement."),
 			NULL
@@ -2054,6 +2072,41 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
+		{"session_pool_size", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets number of backends serving client sessions."),
+			gettext_noop("If non-zero then session pooling will be used: "
+						 "client connections will be redirected to one of the backends and maximal number of backends is determined by this parameter."
+						 "Launched backend are never terminated even in case of no active sessions.")
+		},
+		&SessionPoolSize,
+		10, 0, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"connection_proxies", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets number of connection proxies."),
+			gettext_noop("Postmaster spawns separate worker process for each proxy. Postmaster scatters connections between proxies using one of scheduling policies (round-robin, random, load-balancing)."
+						 "Each proxy launches its own subset of backends. So maximal number of non-tainted backends is "
+						 "session_pool_size*connection_proxies*databases*roles.")
+		},
+		&ConnectionProxiesNumber,
+		0, 0, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+ 	{
+		{"max_sessions", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets the maximum number of client session."),
+			gettext_noop("Maximal number of client sessions which can be handled by ont connection proxy."
+						 "It can be greater than max_connections and actually be arbitrary large.")
+		},
+		&MaxSessions,
+		1000, 1, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
 		/* see max_connections and max_wal_senders */
 		{"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
 			gettext_noop("Sets the number of connection slots reserved for superusers."),
@@ -2101,6 +2154,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
+		{"proxy_port", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
+			gettext_noop("Sets the TCP port for the connection pooler."),
+			NULL
+		},
+		&ProxyPortNumber,
+		6543, 1, 65535,
+		NULL, NULL, NULL
+	},
+
+	{
 		{"unix_socket_permissions", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
 			gettext_noop("Sets the access permissions of the Unix-domain socket."),
 			gettext_noop("Unix-domain sockets use the usual Unix file system "
@@ -4403,6 +4466,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"session_schedule", PGC_POSTMASTER, RESOURCES_MEM,
+			gettext_noop("Session schedule policy for connection pool."),
+			NULL
+		},
+		&SessionSchedule,
+		SESSION_SCHED_ROUND_ROBIN, session_schedule_options,
+		NULL, NULL, NULL
+	},
+
 	/* End-of-list marker */
 	{
 		{NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL
@@ -7815,6 +7888,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
 				 errmsg("cannot set parameters during a parallel operation")));
+	MyProc->is_tainted = true;
 
 	switch (stmt->kind)
 	{
diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 22da98c..d40a9d2 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -506,7 +506,7 @@ MemoryContextStatsDetail(MemoryContext context, int max_children)
  * *totals (if given).
  */
 static void
-MemoryContextStatsInternal(MemoryContext context, int level,
+ MemoryContextStatsInternal(MemoryContext context, int level,
 						   bool print, int max_children,
 						   MemoryContextCounters *totals)
 {
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index acb0154..1e571f1 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -10095,4 +10095,10 @@
   proargnames => '{rootrelid,relid,parentrelid,isleaf,level}',
   prosrc => 'pg_partition_tree' },
 
+{ oid => '3424', descr => 'information about connection pooler proxies workload',
+  proname => 'pg_pooler_state', proretset => 't',
+  provolatile => 'v', prorettype => 'record', proargtypes => '',
+  proallargtypes => '{int4,int4,int4,int4,int4,int4,int8,int8,int8}', proargmodes => '{o,o,o,o,o,o,o,o,o}',
+  proargnames => '{pid,n_clients,n_ssl_clients,n_pools,n_backends,n_dedicated_backends,tx_bytes,rx_bytes,n_transactions}', prosrc => 'pg_pooler_state' },
+
 ]
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index e817524..66033a8 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -54,8 +54,8 @@ extern const PGDLLIMPORT PQcommMethods *PqCommMethods;
  * prototypes for functions in pqcomm.c
  */
 extern int StreamServerPort(int family, char *hostName,
-				 unsigned short portNumber, char *unixSocketDir,
-				 pgsocket ListenSocket[], int MaxListen);
+							unsigned short portNumber, char *unixSocketDir,
+							pgsocket ListenSocket[], int ListenPort[], int MaxListen);
 extern int	StreamConnection(pgsocket server_fd, Port *port);
 extern void StreamClose(pgsocket sock);
 extern void TouchSocketFiles(void);
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index d6b32c0..3fe7de2 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -159,6 +159,19 @@ extern PGDLLIMPORT int data_directory_mode;
 extern PGDLLIMPORT int NBuffers;
 extern PGDLLIMPORT int MaxBackends;
 extern PGDLLIMPORT int MaxConnections;
+
+enum SessionSchedulePolicy
+{
+	SESSION_SCHED_ROUND_ROBIN,
+	SESSION_SCHED_RANDOM,
+	SESSION_SCHED_LOAD_BALANCING
+};
+extern PGDLLIMPORT int MaxSessions;
+extern PGDLLIMPORT int SessionPoolSize;
+extern PGDLLIMPORT int ConnectionProxiesNumber;
+extern PGDLLIMPORT int SessionSchedule;
+extern PGDLLIMPORT bool RestartPoolerOnReload;
+
 extern PGDLLIMPORT int max_worker_processes;
 extern PGDLLIMPORT int max_parallel_workers;
 
diff --git a/src/include/port.h b/src/include/port.h
index 570a905..c03e78b 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -41,6 +41,10 @@ typedef SOCKET pgsocket;
 extern bool pg_set_noblock(pgsocket sock);
 extern bool pg_set_block(pgsocket sock);
 
+/* send/receive socket descriptor */
+extern int pg_send_sock(pgsocket chan, pgsocket sock, pid_t pid);
+extern pgsocket pg_recv_sock(pgsocket chan);
+
 /* Portable path handling for Unix/Win32 (in path.c) */
 
 extern bool has_drive_prefix(const char *filename);
diff --git a/src/include/port/win32_port.h b/src/include/port/win32_port.h
index f9d351f..a4c09e5 100644
--- a/src/include/port/win32_port.h
+++ b/src/include/port/win32_port.h
@@ -445,6 +445,7 @@ extern int	pgkill(int pid, int sig);
 #define select(n, r, w, e, timeout) pgwin32_select(n, r, w, e, timeout)
 #define recv(s, buf, len, flags) pgwin32_recv(s, buf, len, flags)
 #define send(s, buf, len, flags) pgwin32_send(s, buf, len, flags)
+#define socketpair(af, type, protocol, socks) pgwin32_socketpair(af, type, protocol, socks)
 
 SOCKET		pgwin32_socket(int af, int type, int protocol);
 int			pgwin32_bind(SOCKET s, struct sockaddr *addr, int addrlen);
@@ -455,7 +456,8 @@ int			pgwin32_select(int nfds, fd_set *readfs, fd_set *writefds, fd_set *exceptf
 int			pgwin32_recv(SOCKET s, char *buf, int len, int flags);
 int			pgwin32_send(SOCKET s, const void *buf, int len, int flags);
 int			pgwin32_waitforsinglesocket(SOCKET s, int what, int timeout);
-
+int         pgwin32_socketpair(int domain, int type, int protocol, SOCKET socks[2]);
+ 
 extern int	pgwin32_noblock;
 
 #endif							/* FRONTEND */
diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h
index a40d66e..dd78a71 100644
--- a/src/include/postmaster/postmaster.h
+++ b/src/include/postmaster/postmaster.h
@@ -17,6 +17,7 @@
 extern bool EnableSSL;
 extern int	ReservedBackends;
 extern PGDLLIMPORT int PostPortNumber;
+extern PGDLLIMPORT int ProxyPortNumber;
 extern int	Unix_socket_permissions;
 extern char *Unix_socket_group;
 extern char *Unix_socket_directories;
@@ -46,6 +47,11 @@ extern int	postmaster_alive_fds[2];
 
 extern PGDLLIMPORT const char *progname;
 
+extern PGDLLIMPORT void* (*LibpqConnectdbParams)(char const* keywords[], char const* values[]);
+
+struct Proxy;
+struct Port;
+
 extern void PostmasterMain(int argc, char *argv[]) pg_attribute_noreturn();
 extern void ClosePostmasterPorts(bool am_syslogger);
 extern void InitProcessGlobals(void);
@@ -63,6 +69,9 @@ extern Size ShmemBackendArraySize(void);
 extern void ShmemBackendArrayAllocation(void);
 #endif
 
+extern int  ParseStartupPacket(struct Port* port, MemoryContext memctx, void* pkg_body, int pkg_size, bool SSLdone);
+extern int	BackendStartup(struct Port* port, int* backend_pid);
+
 /*
  * Note: MAX_BACKENDS is limited to 2^18-1 because that's the width reserved
  * for buffer references in buf_internals.h.  This limitation could be lifted
diff --git a/src/include/postmaster/proxy.h b/src/include/postmaster/proxy.h
new file mode 100644
index 0000000..7f7a92a
--- /dev/null
+++ b/src/include/postmaster/proxy.h
@@ -0,0 +1,43 @@
+/*-------------------------------------------------------------------------
+ *
+ * proxy.h
+ *	  Exports from postmaster/proxy.c.
+ *
+ * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/postmaster/proxy.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PROXY_H
+#define _PROXY_H
+
+/*
+ * Information in share dmemory about connection proxy state (used for session scheduling and monitoring)
+ */
+typedef struct ConnectionProxyState
+{
+	int pid;                  /* proxy worker pid */
+	int n_clients;            /* total number of clients */
+	int n_ssl_clients;        /* number of clients using SSL connection */
+	int n_pools;              /* nubmer of dbname/role combinations */
+	int n_backends;           /* totatal number of launched backends */
+	int n_dedicated_backends; /* number of tainted backends */
+	uint64 tx_bytes;          /* amount of data sent to client */
+	uint64 rx_bytes;          /* amount of data send to server */
+	uint64 n_transactions;    /* total number of proroceeded transactions */
+} ConnectionProxyState;
+
+extern ConnectionProxyState* ProxyState;
+extern PGDLLIMPORT int MyProxyId;
+extern PGDLLIMPORT pgsocket MyProxySocket;
+
+extern int  ConnectionProxyStart(void);
+extern int  ConnectionProxyShmemSize(void);
+extern void ConnectionProxyShmemInit(void);
+#ifdef EXEC_BACKEND
+extern void ConnectionProxyMain(int argc, char *argv[]);
+#endif
+
+#endif
diff --git a/src/include/storage/latch.h b/src/include/storage/latch.h
index 039a82e..89f1c1b 100644
--- a/src/include/storage/latch.h
+++ b/src/include/storage/latch.h
@@ -133,9 +133,11 @@ typedef struct Latch
 /* avoid having to deal with case on platforms not requiring it */
 #define WL_SOCKET_CONNECTED  WL_SOCKET_WRITEABLE
 #endif
+#define WL_SOCKET_EDGE       (1 << 7)
 
 #define WL_SOCKET_MASK		(WL_SOCKET_READABLE | \
 							 WL_SOCKET_WRITEABLE | \
+							 WL_SOCKET_EDGE | \
 							 WL_SOCKET_CONNECTED)
 
 typedef struct WaitEvent
@@ -177,6 +179,8 @@ extern int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout,
 extern int WaitLatchOrSocket(volatile Latch *latch, int wakeEvents,
 				  pgsocket sock, long timeout, uint32 wait_event_info);
 
+extern void DeleteWaitEventFromSet(WaitEventSet *set, int event_pos);
+
 /*
  * Unix implementation uses SIGUSR1 for inter-process signaling.
  * Win32 doesn't need this.
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index cb613c8..d4b728e 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -203,6 +203,8 @@ struct PGPROC
 	PGPROC	   *lockGroupLeader;	/* lock group leader, if I'm a member */
 	dlist_head	lockGroupMembers;	/* list of members, if I'm a leader */
 	dlist_node	lockGroupLink;	/* my member link, if I'm a member */
+
+	bool        is_tainted;            /* backend has modified session GUCs, use temporary tables, prepare statements, ... */
 };
 
 /* NOTE: "typedef struct PGPROC PGPROC" appears in storage/lock.h. */
diff --git a/src/include/utils/guc_tables.h b/src/include/utils/guc_tables.h
index 6f9fdb6..455e3e9 100644
--- a/src/include/utils/guc_tables.h
+++ b/src/include/utils/guc_tables.h
@@ -58,6 +58,7 @@ enum config_group
 	CONN_AUTH_SETTINGS,
 	CONN_AUTH_AUTH,
 	CONN_AUTH_SSL,
+	CONN_POOLING,
 	RESOURCES,
 	RESOURCES_MEM,
 	RESOURCES_DISK,
diff --git a/src/makefiles/Makefile.cygwin b/src/makefiles/Makefile.cygwin
index 3aaa8a9..c172e10 100644
--- a/src/makefiles/Makefile.cygwin
+++ b/src/makefiles/Makefile.cygwin
@@ -17,6 +17,7 @@ CFLAGS_SL =
 ifneq (,$(findstring backend,$(subdir)))
 ifeq (,$(findstring conversion_procs,$(subdir)))
 ifeq (,$(findstring libpqwalreceiver,$(subdir)))
+ifeq (,$(findstring libpqconn,$(subdir)))
 ifeq (,$(findstring replication/pgoutput,$(subdir)))
 ifeq (,$(findstring snowball,$(subdir)))
 override CPPFLAGS+= -DBUILDING_DLL
diff --git a/src/makefiles/Makefile.win32 b/src/makefiles/Makefile.win32
index 7abbd01..7566f51 100644
--- a/src/makefiles/Makefile.win32
+++ b/src/makefiles/Makefile.win32
@@ -15,6 +15,7 @@ CFLAGS_SL =
 ifneq (,$(findstring backend,$(subdir)))
 ifeq (,$(findstring conversion_procs,$(subdir)))
 ifeq (,$(findstring libpqwalreceiver,$(subdir)))
+ifeq (,$(findstring libpqconn,$(subdir)))
 ifeq (,$(findstring replication/pgoutput,$(subdir)))
 ifeq (,$(findstring snowball,$(subdir)))
 override CPPFLAGS+= -DBUILDING_DLL

---

From: Bruce Momjian <[email-masked]>
Date: Mon, 28 Jan 2019 16:10:40 -0500

On Thu, Jan 24, 2019 at 08:14:41PM +0300, Konstantin Knizhnik wrote:
> 3. It supports all clients (if client needs session semantic, then it will be
> implicitly given dedicated backend)
> 
> 
> ┌────────────────┬────────┬─────────────┬─────────┬─────────────────────────┐
> │ #Connections   │ Proxy  │ Proxy/SSL   │ Direct  │ Direct/SSL   │
> ├────────────────┼────────┼─────────────┼─────────┼──────────────┤
> │ 1              │  13752 │       12396 │   17443 │        15762 │
> ├────────────────┼────────┼─────────────┼─────────┼──────────────┤
> │ 10             │  53415 │       59615 │   68334 │        85885 │
> ├────────────────┼────────┼─────────────┼─────────┼──────────────┤
> │ 1000           │  60152 │       20445 │   60003 │        24047 │
> └────────────────┴────────┴─────────────┴─────────┴──────────────┘

It is nice it is a smaller patch.  Please remind me of the performance
advantages of this patch.

-- 
  Bruce Momjian  <[email-masked]>        http://momjian.us
  EnterpriseDB                             http://enterprisedb.com

+ As you are, so once was I.  As I am, so you will be. +
+                      Ancient Roman grave inscription +

---

From: Dimitri Fontaine <[email-masked]>
Date: Mon, 28 Jan 2019 22:33:06 +0100

Hi,

> advantages of this patch.

The patch as it stands is mostly helpful in those situations:

  - application server(s) start e.g. 2000 connections at start-up and
    then use them depending on user traffic

    It's then easy to see that if we would only fork as many backends as
    we need, while having accepted the 2000 connections without doing
    anything about them, we would be in a much better position than when
    we fork 2000 unused backends.

  - application is partially compatible with pgbouncer transaction
    pooling mode

    Then in that case, you would need to run with pgbouncer in session
    mode. This happens when the application code is using session level
    SQL commands/objects, such as prepared statements, temporary tables,
    or session-level GUCs settings.

    With the attached patch, if the application sessions profiles are
    mixed, then you dynamically get the benefits of transaction pooling
    mode for those sessions which are not “tainting” the backend, and
    session pooling mode for the others.

    It means that it's then possible to find the most often used session
    and fix that one for immediate benefits, leaving the rest of the
    code alone. If it turns out that 80% of your application sessions
    are the same code-path and you can make this one “transaction
    pooling” compatible, then you most probably are fixing (up to) 80%
    of your connection-related problems in production.

  - applications that use a very high number of concurrent sessions

    In that case, you can either set your connection pooling the same as
    max_connection and see no benefits (and hopefully no regressions
    either), or set a lower number of backends serving a very high
    number of connections, and have sessions waiting their turn at the
    “proxy” stage.

    This is a kind of naive Admission Control implementation where it's
    better to have active clients in the system wait in line consuming
    as few resources as possible. Here, in the proxy. It could be done
    with pgbouncer already, this patch gives a stop-gap in PostgreSQL
    itself for those use-cases.

    It would be mostly useful to do that when you have queries that are
    benefiting of parallel workers. In that case, controling the number
    of active backend forked at any time to serve user queries allows to
    have better use of the parallel workers available.

In other cases, it's important to measure and accept the possible
performance cost of running a proxy server between the client connection
and the PostgreSQL backend process. I believe the numbers shown in the
previous email by Konstantin are about showing the kind of impact you
can see when using the patch in a use-case where it's not meant to be
helping much, if at all.

Regards,
-- 
dim

---

From: Michael Paquier <[email-masked]>
Date: Tue, 29 Jan 2019 14:14:03 +0900

> can see when using the patch in a use-case where it's not meant to be

Have you looked at the possibility of having the proxy worker be
spawned as a background worker?  I think that we should avoid spawning
any new processes on the backend from the ground as we have a lot more
infrastructures since 9.3.  The patch should actually be bigger, the
code is very raw and lacks comments in a lot of areas where the logic
is not so obvious, except perhaps to the patch author.
--
Michael

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 29 Jan 2019 12:09:50 +0300

> advantages of this patch.
The primary purpose of pooler is efficient support of large number of 
connections and minimizing system resource usage.
But as far as Postgres is not scaling well at SMP system with larger 
number of CPU cores (due to many reasons discussed in hackers)
reducing number of concurrently working backends can also significantly 
increase performance.

I have not done such testing yet but I am planing to do it as well as 
comparison with pgbouncer and Odyssey.
But please notice that this proxy approach is by design slower than my 
previous implementation used in PgPRO-EE (based on socket redirection).
At some workloads connections throughout proxy cause up to two times 
decrease of performance comparing with dedicated backends.
There is no such problem with old connection pooler implementation which 
was always not worser than vanilla. But it doesn't support SSL connections
and requires much more changes in Postgres core.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 29 Jan 2019 12:21:33 +0300

On 29.01.2019 8:14, Michael Paquier wrote:
> spawned as a background worker?

Yes, it was my first attempt.
The main reason why I have implemented it in old ways are:
1. I need to know PID of spawned worker. Strange - it is possible to get 
PID of dynamic bgworker, but no of static one.
Certainly it is possible  to find a way of passing this PID to 
postmaster but it complicates start of worker.
2. I need to pass socket to spawner proxy.  Once again: it can be 
implemented also with bgworker but requires more coding (especially 
taken in account support of Win32 and FORKEXEC mode).

>   I think that we should avoid spawning

The main reason for publishing this patch was to receive feedbacks and 
find places which should be rewritten.
I will add more comments but I will be pleased if you point me which 
places are obscure now and require better explanation.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 20 Mar 2019 18:32:03 +0300

Attached please find results of benchmarking of different connection 
poolers.

Hardware configuration:
    Intel(R) Xeon(R) CPU           X5675  @ 3.07GHz
    24 cores (12 physical)
    50 GB RAM

Tests:
      pgbench read-write (scale 1): performance is mostly limited by 
disk throughput
      pgbench select-only (scale 1): performance is mostly limited by 
efficient utilization of CPU by all workers
      pgbench with YCSB-like workload with Zipf distribution: 
performance is mostly limited by lock contention

Participants:
     1. pgbouncer (16 and 32 pool size, transaction level pooling)
     2. Postgres Pro-EE connection poller: redirection of client 
connection to poll workers and maintaining of session contexts.
         16 and 32 connection pool size (number of worker backend).
     3. Built-in proxy connection pooler: implementation proposed in 
this thread.
         16/1 and 16/2 specifies number of worker backends per proxy and 
number of proxies, total number of backends is multiplication of this 
values.
     4. Yandex Odyssey (32/2 and 64/4 configurations specifies number of 
backends and Odyssey threads).
     5. Vanilla Postgres (marked at diagram as "12devel-master/2fadf24 
POOL=none")

In all cases except 2) master branch of Postgres is used.
Client (pgbench), pooler and postgres are laucnhed at the same host. 
Communication is though loopback interface (host=localhost).
We have tried to find the optimal parameters for each pooler.
Three graphics attached to the mail illustrate three different test cases.

Few comments about this results:
- PgPro EE pooler shows the best results in all cases except tpc-b like. 
In this case proxy approach is more efficient because more flexible job 
schedule between workers
   (in EE sessions are scattered between worker backends at connect 
time, while proxy chooses least loaded backend for each transaction).
- pgbouncer is not able to scale well because of its single-threaded 
architecture. Certainly it is possible to spawn several instances of 
pgbouncer and scatter
   workload between them. But we have not did it.
- Vanilla Postgres demonstrates significant degradation of performance 
for large number of active connections on all workloads except read-only.
- Despite to the fact that Odyssey is new player (or may be because of 
it), Yandex pooler doesn't demonstrate good results. It is the only 
pooler which also cause degrade of performance with increasing number of 
connections. May be it is caused by memory leaks, because it memory 
footprint is also actively increased during test.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 20 Mar 2019 18:33:42 +0300

New version of the patch (rebased + bug fixes) is attached to this mail.

On 20.03.2019 18:32, Konstantin Knizhnik wrote:
>         16/1 and 16/2 specifies number of worker backends per proxy 
> and number of proxies, total number of backends is multiplication of 
> this values.
>     4. Yandex Odyssey (32/2 and 64/4 configurations specifies number 
> of backends and Odyssey threads).
> - PgPro EE pooler shows the best results in all cases except tpc-b 
> like. In this case proxy approach is more efficient because more 
> flexible job schedule between workers
> pooler which also cause degrade of performance with increasing number 
> of connections. May be it is caused by memory leaks, because it memory 

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index d383de2..bee9725 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -719,6 +719,123 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
index a03ea14..8179918 100644

  </part>
 
index fc231ca..f77f299 100644
@@ -457,6 +458,7 @@ StorePreparedStatement(const char *stmt_name,
 
 	/* Shouldn't get a duplicate entry */
 	if (found)
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 515c290..cf851bd 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -561,6 +561,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index c39617a..522ff94 100644

+	if (FeBeWaitSet)
 
+

 
 
index 0000000..dd5caa0
@@ -0,0 +1,165 @@
+		elog(WARNING, "Failed to transfer socket");
index d5b5e77..53eece6 100644

index 0000000..bdba0f6
@@ -0,0 +1,47 @@
+void _PG_init(void);
index fe59963..e1d4b87 100644

 
 /*
  * Set by the -o option
 
@@ -403,7 +420,6 @@ static void BackendInitialize(Port *port);
@@ -425,6 +441,7 @@ static pid_t StartChildProcess(AuxProcType type);
 
 /*
  * Archiver is allowed to start up at the current postmaster state?
@@ -477,6 +494,8 @@ typedef struct
 {
 	Port		port;
 	InheritableSocket portsocket;
+	InheritableSocket proxySocket;
+	int         proxyId;
 	char		DataDir[MAXPGPATH];
 	pgsocket	ListenSocket[MAXLISTEN];
 	int32		MyCancelKey;
@@ -559,6 +578,48 @@ int			postmaster_alive_fds[2] = {-1, -1};
 HANDLE		PostmasterHandle;
 #endif
 
+static void
+			ConnectionProxies = malloc(sizeof(ConnectionProxy)*ConnectionProxiesNumber);
@@ -571,6 +632,9 @@ PostmasterMain(int argc, char *argv[])
 
 	InitProcessGlobals();
 
@@ -1067,6 +1131,11 @@ PostmasterMain(int argc, char *argv[])

@@ -1090,32 +1159,36 @@ PostmasterMain(int argc, char *argv[])
 
@@ -1184,29 +1257,32 @@ PostmasterMain(int argc, char *argv[])

@@ -1216,6 +1292,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
@@ -1373,6 +1463,8 @@ PostmasterMain(int argc, char *argv[])

 	/*
@@ -1610,6 +1702,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
@@ -1700,8 +1843,18 @@ ServerLoop(void)
 						 * We no longer need the open socket or port structure
 						 * in this process
@@ -1895,8 +2048,6 @@ ProcessStartupPacket(Port *port, bool SSLdone)
 
 	pq_startmsgread();
 
@@ -1962,6 +2113,18 @@ ProcessStartupPacket(Port *port, bool SSLdone)
 	}
 	pq_endmsgread();
 
+	am_walsender = false;
+	am_db_walsender = false;
@@ -2036,7 +2199,7 @@ retry1:
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2703,6 +2866,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
@@ -2780,6 +2945,9 @@ pmdie(SIGNAL_ARGS)
 
@@ -4009,6 +4177,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4018,8 +4187,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4123,6 +4292,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4819,6 +4990,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -4959,6 +5131,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5027,7 +5212,6 @@ ExitPostmaster(int status)
 				 errdetail("Please report this to <[email-masked]>.")));
 
 	/*
@@ -5485,6 +5669,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
@@ -6062,6 +6314,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6290,6 +6546,9 @@ restore_backend_variables(BackendParameters *param, Port *port)
 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);

index 0000000..d7fcc7f
@@ -0,0 +1,1024 @@
+#include "replication/walsender.h"
+ * Channels represent both clients and backends
+	bool     backend_is_tainted; /* client changes session context */
+	bool     is_disconnected;    /* connection is lost */
+	/* We need to save startup packet response to be able to send it to new connection */
+ * Control structure for connection proxies (several proxy workers can be launched and each has it sown proxy instance).
+ * Proxy contains hash of session pools for reach role/dbname combination.
+									  * (startup packet is not received and db/role are not known) */
+	Channel* hangout;            /* List of disconnected backends */
+ * Connection pool to particular role/dbname
+	Channel* idle_backends;       /* List of idle clients */
+	Channel* pending_clients;     /* List of clients waiting for free backend */
+	Proxy*   proxy;               /* Owner of this pool */
+//#define ELOG(severity, fmt,...) elog(severity, "PROXY: " fmt, ## __VA_ARGS__)
+ * Now if backend is not tainted it is possible to schedule some other client to this backend.
+		if (chan->peer)
+			Assert(chan != pending);
+				Assert(chan->handshake_response != NULL); /* backend already sent handshake response */
+			Assert(!chan->client_port);
+	/* parse startup packet in tmpctx memory context and reset it when it is not needed any more */
+	/* Associate libpq with client's port */
+		MyProcPort = NULL;
+	MyProcPort = NULL;
+	if (am_walsender)
+		elog(WARNING, "WAL sender should not be connected through proxy");
+	pg_set_noblock(chan->client_port->sock); /* SSL handshake may switch socket to blocking mode */
+		/* First connection to this role/dbname */
+		/* has some idle backend */
+		Assert(!idle_backend->backend_is_tainted && !idle_backend->client_port);
+		Assert(chan != idle_backend);
+				Assert(chan != idle_backend);
+		/* Postpone handshake until some backend is available */
+	Channel** ipp;
+		for (ipp = &chan->pool->pending_clients; *ipp != NULL; ipp = &(*ipp)->next) {
+			if (*ipp == chan) {
+				*ipp = chan->next;
+		for (ipp = &chan->pool->idle_backends; *ipp != NULL; ipp = &(*ipp)->next) {
+			if (*ipp == chan) {
+				*ipp = chan->next;
+	if (peer)
+		peer->peer = NULL;
+	if (chan->client_port && peer) /* If it is client connected to backend. */
+		if (!chan->is_interrupted) /* Client didn't sent 'X' command, so do it for him. */
+			ELOG(LOG, "Send terminate command to backend %p (pid %d)", peer, peer->backend_pid);
+			peer->is_interrupted = true; /* interrupted flags makes channel_write to send 'X' message */
+		else if (!peer->is_interrupted)
+			/* Client already sent 'X' command, so we can safely reschedule backend to some other client session */
+ * Data is located in the peer buffer. Because of using edge-triggered mode we have have to use non-blocking IO
+ * and try to write all available data. Once write is completed we should try to read more data from source socket.
+ * "synchronous" flag is used to avoid infinite recursion or reads-writers.
+ * Returns true if there is nothing to do or operation is successfully completed, false in case of error
+		/* Send terminate command to the backend. */
+		/* Copy rest of received data to the beginning of the buffer */
+		if (peer->backend_is_ready) {
+			Assert(peer->rx_pos == 0);
+		/* Loop through all received messages */
+		while (chan->rx_pos - msg_start >= 5) /* has message code + length */
+				/* Reallocate buffer to fit complete message body */
+						/* Some trouble with processing startup packet */
+				else if (!chan->client_port /* Message from backend */
+					&& chan->buf[msg_start] == 'Z'  /* Ready for query */
+					Assert(chan->rx_pos - msg_start == msg_len); /* Should be last message */
+					chan->backend_is_ready = true; /* Backend is ready for query */
+				else if (chan->client_port /* Message from client */
+						 && chan->buf[msg_start] == 'X')	/* Terminate message */
+					if (handshake) /* Send handshake response to the client */
+                        /* If we attach new client to the existed backend, then we need to send handshake response to the client */
+						chan->rx_pos = 0; /* Skip startup packet */
+						if (backend != NULL) /* Backend was assigned */
+							Assert(backend->handshake_response != NULL); /* backend has already sent handshake responses */
+							backend->backend_is_ready = true;
+							/* Handshake response will be send to client later when backend is assigned */
+					else if (chan->peer == NULL) /* Backend was not assigned */
+			else break; /* Incomplete message. */
+			/* Has some complete messages to send to peer */
+		/* If backend is out of transaction, then reschedule it */
+ * Create new channel.
+ * Register new channel in wait event set.
+	/* Using edge epoll mode requires non-blocking sockets */
+	char const* keywords[] = {"port","dbname","user","sslmode","application_name",NULL};
+	char const* values[] = {postmaster_port,pool->key.database,pool->key.username,"disable","pool_worker",NULL};
+		/* We need libpq library to be able to establish connections to pool workers.
+		* This library can not be linked statically, so load it on demand. */
+	/* Using edge epoll mode requires non-blocking sockets */
+	while (*msg != 'K') /* Scan handshake response until we reach PID message */
+		/* Too much sessions, error report was already logged */
+ * Add new client accepted by postmaster. This client will be assigned to concrete session pool
+	if (channel_register(proxy, chan))
+		/* Too much sessions, error report was already logged */
+		close(port->sock);
+		free(port);
+	 /* We need events both for clients and backends so multiply MaxConnection by two */
+	proxy->wait_events = CreateWaitEventSet(TopMemoryContext, MaxSessions*2);
+	/* Main loop */
+					elog(WARNING, "Failed to receive session socket: %m");
+					free(port);
+		 * Delayed deallocation of disconnected channels.
+		 * We can not delete channels immediately because of presence of peer events.
+ * Handle normal shutdown of Postgres instance
+ * Function for launching proxy by postmaster.
+ * This "boilerplate" code is taken from another auxiliary workers.
+ * In future it may be replaced with background worker.
+ * The main problem with background worker is how to pass socket to it and obtains its PID.
+ * We need some place in shared memory to provide information about proxies state.
+ * Return information about proxies state.
+ * This set-returning functions returns the following columns:
+ * pid            - proxy process identifier
+ * n_clients      - number of clients connected to proxy
+ * n_ssl_clients  - number of clients using SSL protocol
+ * n_pools        - number of pools (role/dbname combinations) maintained by proxy
+ * n_backends     - total number of backends spawned by this proxy (including tainted)
+ * n_dedicated_backends - number of tainted backend
+ * tx_bytes       - amount of data sent from backends to clients
+ * rx_bytes       - amount of data sent from client to backends
+ * n_transactions - number of transaction proceeded by all backends of this proxy
index 5965d36..85affef 100644

 	/*
index 59fa917..da651d0 100644
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

index f9ce3d8..8955f0a 100644
@@ -4215,6 +4215,8 @@ PostgresMain(int argc, char *argv[],
index ffd1970..16ca58d 100644
 
index a5950c1..b4b531f 100644

 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index cdb6a61..41e59d8 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -455,6 +455,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
+static const struct config_enum_entry session_schedule_options[] = {
+	{"round-robin", SESSION_SCHED_ROUND_ROBIN, false},
+	{"random", SESSION_SCHED_RANDOM, false},
+	{"load-balancing", SESSION_SCHED_LOAD_BALANCING, false},
+	{NULL, 0, false}
+};
+
+
 static struct config_enum_entry shared_memory_options[] = {
 #ifndef WIN32
 	{ "sysv", SHMEM_TYPE_SYSV, false},
@@ -1245,6 +1253,16 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
@@ -2088,6 +2106,42 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
+		/* see max_connections and max_wal_senders */
 		/* see max_connections */
@@ -2135,6 +2189,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4458,6 +4522,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8033,6 +8107,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 	switch (stmt->kind)
 	{
diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 43c58c3..a964d75 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -506,7 +506,7 @@ MemoryContextStatsDetail(MemoryContext context, int max_children)
  * *totals (if given).
  */
 static void
-MemoryContextStatsInternal(MemoryContext context, int level,
+ MemoryContextStatsInternal(MemoryContext context, int level,
 						   bool print, int max_children,
 						   MemoryContextCounters *totals)
 {
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index c4b012c..1823aa1 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -10570,4 +10570,11 @@
   proname => 'pg_partition_root', prorettype => 'regclass',
   proargtypes => 'regclass', prosrc => 'pg_partition_root' },
 
+# builin connection pool
+{ oid => '3435', descr => 'information about connection pooler proxies workload',
+  proname => 'pg_pooler_state', prorows => '1000', proretset => 't',
index 755819c..3156d08 100644
index b677c7e..710e0a6 100644
 
index 7e2004b..dac878e 100644

index f4841fb..e101df1 100644

 #endif							/* FRONTEND */
index 8ccd2af..05906e9 100644

 
index fc99581..6e9696b 100644

 typedef struct WaitEvent
@@ -177,6 +179,8 @@ extern int WaitLatch(Latch *latch, int wakeEvents, long timeout,
 extern int WaitLatchOrSocket(Latch *latch, int wakeEvents,
 				  pgsocket sock, long timeout, uint32 wait_event_info);
 
index 1cee7db..291d4ec 100644
 
index a0970b2..f3c8efe 100644

---

From: Thomas Munro <[email-masked]>
Date: Mon, 1 Jul 2019 21:57:50 +1200

> New version of the patch (rebased + bug fixes) is attached to this mail.

Hi again Konstantin,

Interesting work.  No longer applies -- please rebase.

-- 
Thomas Munro
https://enterprisedb.com

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 1 Jul 2019 18:11:26 +0300

> Interesting work.  No longer applies -- please rebase.
Rebased version of the patch is attached.
Also all this version of built-ni proxy can be found in conn_proxy 
branch of https://github.com/postgrespro/postgresql.builtin_pool.git
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 84341a30e5..9398e561e8 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -719,6 +719,123 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
index 0000000000..07f4202f75
index 8960f11278..5b19fef481 100644
 
index 3e115f1c76..029f0dc4e3 100644
 
  </part>
 
index bcdbd9588a..196ca8c0f0 100644
index c278ee7318..acbaed313a 100644
 
 	/* Shouldn't get a duplicate entry */
 	if (found)
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index fd67d2a841..10a14d0e03 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -590,6 +590,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index 384887e70d..ebff20a61a 100644

+	if (FeBeWaitSet)
 
+

index f4120bec55..e0cdd9e8bb 100644

index 0000000000..dd5caa0724
index d5b5e771e9..53eece6422 100644
index 71c23211b2..9622ee79cb 100644

index 0000000000..f05b72758e
index 0000000000..bdba0f6e2c
index 688ad439ed..b75aedfc86 100644

 
 /*
  * Set by the -o option
 
 static int	ProcessStartupPacket(Port *port, bool secure_done);
 
 /*
@@ -560,6 +579,48 @@ int			postmaster_alive_fds[2] = {-1, -1};
 HANDLE		PostmasterHandle;
 #endif
 
+static void
@@ -572,6 +633,9 @@ PostmasterMain(int argc, char *argv[])
 
 	InitProcessGlobals();
 
@@ -1008,6 +1072,11 @@ PostmasterMain(int argc, char *argv[])

@@ -1031,32 +1100,36 @@ PostmasterMain(int argc, char *argv[])
 
@@ -1125,29 +1198,32 @@ PostmasterMain(int argc, char *argv[])

@@ -1157,6 +1233,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
@@ -1374,6 +1464,8 @@ PostmasterMain(int argc, char *argv[])

 	/*
@@ -1611,6 +1703,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
@@ -1701,8 +1844,18 @@ ServerLoop(void)
@@ -1899,8 +2052,6 @@ ProcessStartupPacket(Port *port, bool secure_done)
 
 	pq_startmsgread();
 
@@ -1967,6 +2118,18 @@ ProcessStartupPacket(Port *port, bool secure_done)
 	}
 	pq_endmsgread();
 
+	return ParseStartupPacket(port, TopMemoryContext, buf, len, secure_done);
+}
+
+int
+ParseStartupPacket(Port *port, MemoryContext memctx, void* buf, int len, bool secure_done)
+{
+	ProtocolVersion proto;
+	MemoryContext oldcontext;
+
+	am_walsender = false;
+	am_db_walsender = false;
+
 	/*
 	 * The first field is either a protocol version number or a special
 	 * request code.
@@ -2067,7 +2230,7 @@ retry1:
 	 * not worry about leaking this storage on failure, since we aren't in the
 	 * postmaster process anymore.
 	 */
-	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
+	oldcontext = MemoryContextSwitchTo(memctx);
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2739,6 +2902,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
@@ -2816,6 +2981,9 @@ pmdie(SIGNAL_ARGS)
 
@@ -4041,6 +4209,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4050,8 +4219,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4155,6 +4324,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4851,6 +5022,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -4991,6 +5163,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5059,7 +5244,6 @@ ExitPostmaster(int status)
 
 	/*
@@ -5525,6 +5709,74 @@ StartAutovacuumWorker(void)
 	}
 }
 
+/*
+ * StartProxyWorker
@@ -6116,6 +6368,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6347,6 +6603,9 @@ restore_backend_variables(BackendParameters *param, Port *port)
 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);

index 0000000000..9616bbe5f2
+			: send(chan->backend_socket, buf, size, 0);
+				: recv(chan->backend_socket, chan->buf + chan->rx_pos, chan->buf_size - chan->rx_pos, 0);
index d7d733530f..6d32d8fe8d 100644
@@ -150,6 +151,7 @@ CreateSharedMemoryAndSemaphores(int port)
 
@@ -255,6 +257,7 @@ CreateSharedMemoryAndSemaphores(int port)
 
 	/*
index 2426cbcf8e..b5f66519d0 100644
 
 	/*

 
 	/* not enough space */

@@ -748,14 +763,29 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
+/*

 

 	/*
@@ -852,21 +884,39 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
+
+	if (action == EPOLL_CTL_DEL)
+	{
+		int pos = event->pos;
+		event->fd = PGINVALID_SOCKET;
+		set->nevents -= 1;
+		event->pos = set->free_events;
+		set->free_events = pos;
+	}
 }
 #endif

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;
@@ -897,9 +947,25 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -912,7 +978,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
@@ -929,8 +995,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 
@@ -1336,7 +1402,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
index 44a59e1d4f..62ec2afd2e 100644
@@ -4217,6 +4217,8 @@ PostgresMain(int argc, char *argv[],
index ffd1970f58..16ca58d9d0 100644
 
index 3bf96de256..79001ccf91 100644

 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 92c4fee8f8..65f66db8e9 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -457,6 +457,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
+static const struct config_enum_entry session_schedule_options[] = {
+	{"round-robin", SESSION_SCHED_ROUND_ROBIN, false},
+	{"random", SESSION_SCHED_RANDOM, false},
+	{"load-balancing", SESSION_SCHED_LOAD_BALANCING, false},
+	{NULL, 0, false}
+};
+
+
 static struct config_enum_entry shared_memory_options[] = {
 #ifndef WIN32
 	{"sysv", SHMEM_TYPE_SYSV, false},
@@ -1285,6 +1293,16 @@ static struct config_bool ConfigureNamesBool[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"restart_pooler_on_reload", PGC_SIGHUP, CONN_POOLING,
+		 gettext_noop("Restart session pool workers on pg_reload_conf()."),
+		 NULL,
+		},
+		&RestartPoolerOnReload,
+		false,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"log_duration", PGC_SUSET, LOGGING_WHAT,
 			gettext_noop("Logs the duration of each completed SQL statement."),
@@ -2137,6 +2155,42 @@ static struct config_int ConfigureNamesInt[] =
 		check_maxconnections, NULL, NULL
 	},
 
+	{
@@ -2184,6 +2238,16 @@ static struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -4550,6 +4614,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8145,6 +8219,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 	switch (stmt->kind)
 	{
index b07be12236..dac74a272d 100644
index 87335248a0..5f528c1d72 100644
@@ -10677,4 +10677,11 @@
 
index 08a257616d..1e12ee1884 100644
@@ -54,10 +54,9 @@ extern const PGDLLIMPORT PQcommMethods *PqCommMethods;
 extern WaitEventSet *FeBeWaitSet;
-extern int	StreamServerPort(int family, char *hostName,
+extern int StreamServerPort(int family, char *hostName,
index 61a24c2e3c..86c0ef84e5 100644
 
index b5c03d912b..3ea24a3b70 100644

index f4841fb397..e101df179f 100644

 #endif							/* FRONTEND */
index 8ccd2afce5..05906e94a0 100644

 
index 0000000000..7f7a92a56a
index bd7af11a8a..680eb5ee10 100644

 typedef struct WaitEvent
 
index ac7ee72952..e7207e2d9a 100644
 
index d68976fafa..9ff45b190a 100644
index f274d802b1..fdf53e9a8d 100644
@@ -19,6 +19,7 @@ override CPPFLAGS += -DWIN32_STACK_RLIMIT=$(WIN32_STACK_RLIMIT)
index 3dea11e5c2..39bd2de85e 100644

---

From: Thomas Munro <[email-masked]>
Date: Mon, 8 Jul 2019 12:37:08 +1200

> branch of https://github.com/postgrespro/postgresql.builtin_pool.git

Thanks Konstantin.  I haven't looked at the code, but I can't help
noticing that this CF entry and the autoprepare one are both features
that come up again an again on feature request lists I've seen.
That's very cool.  They also both need architectural-level review.
With my Commitfest manager hat on: reviewing other stuff would help
with that; if you're looking for something of similar complexity and
also the same level of
everyone-knows-we-need-to-fix-this-!@#$-we-just-don't-know-exactly-how-yet
factor, I hope you get time to provide some more feedback on Takeshi
Ideriha's work on shared caches, which doesn't seem a million miles
from some of the things you're working on.

Could you please fix these compiler warnings so we can see this
running check-world on CI?

https://ci.appveyor.com/project/postgresql-cfbot/postgresql/build/1.0.46324
https://travis-ci.org/postgresql-cfbot/postgresql/builds/555180678

-- 
Thomas Munro
https://enterprisedb.com

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 8 Jul 2019 23:30:06 +0300

> from some of the things you're working on.

Thank you, I will look at Takeshi Ideriha's patch.

> https://travis-ci.org/postgresql-cfbot/postgresql/builds/555180678
Sorry, I do not have access to Windows host, so can not check Win32 
build myself.
I have fixed all the reported warnings but can not verify that Win32 
build is now ok.

 
 
  </part>

 

+	if (FeBeWaitSet)
 
+

 
 
index 0000000000..e395868eef
+	rc = send(chan, (char*)&dst, sizeof(dst), 0);
+	size_t rc = recv(chan, (char*)&src, sizeof(src), 0);
index 71c23211b2..5d8b65c50a 100644
@@ -12,7 +12,9 @@ subdir = src/backend/postmaster
 
+override CPPFLAGS :=  $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
+
 OBJS = autovacuum.o bgworker.o bgwriter.o checkpointer.o fork_process.o \
-	pgarch.o pgstat.o postmaster.o startup.o syslogger.o walwriter.o
+	pgarch.o pgstat.o postmaster.o startup.o syslogger.o walwriter.o proxy.o
 
index 688ad439ed..73a695b5ee 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }
 
+		CreateSharedMemoryAndSemaphores(0);
 
 	/*
 
+/*
+ * StartProxyWorker

 
 
 	strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
+
+	read_inheritable_socket(&MyProxySocket, &param->proxySocket);
+	MyProxyId = param->proxyId;
 }

index 0000000000..ab058fa5f9
+		rc = be_tls_write(chan->client_port, (char*)buf, size, &waitfor);

 	/*
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 

 
 
+	{
 
+	{
 
+	{
 
+	{
 
 	switch (stmt->kind)
 	{

 

 
 #endif							/* FRONTEND */

 

 typedef struct WaitEvent

---

From: Thomas Munro <[email-masked]>
Date: Sun, 14 Jul 2019 17:03:27 +1200

>>>> Rebased version of the patch is attached.

Thanks for including nice documentation in the patch, which gives a
good overview of what's going on.  I haven't read any code yet, but I
took it for a quick drive to understand the user experience.  These
are just some first impressions.

I started my server with -c connection_proxies=1 and tried to connect
to port 6543 and the proxy segfaulted on null ptr accessing
port->gss->enc.  I rebuilt without --with-gssapi to get past that.

Using SELECT pg_backend_pid() from many different connections, I could
see that they were often being served by the same process (although
sometimes it created an extra one when there didn't seem to be a good
reason for it to do that).  I could see the proxy managing these
connections with SELECT * FROM pg_pooler_state() (I suppose this would
be wrapped in a view with a name like pg_stat_proxies).  I could see
that once I did something like SET foo.bar = 42, a backend became
dedicated to my connection and no other connection could use it.  As
described.  Neat.

Obviously your concept of tainted backends (= backends that can't be
reused by other connections because they contain non-default session
state) is quite simplistic and would help only the very simplest use
cases.  Obviously the problems that need to be solved first to do
better than that are quite large.  Personally I think we should move
all GUCs into the Session struct, put the Session struct into shared
memory, and then figure out how to put things like prepared plans into
something like Ideriha-san's experimental shared memory context so
that they also can be accessed by any process, and then we'll mostly
be tackling problems that we'll have to tackle for threads too.  But I
think you made the right choice to experiment with just reusing the
backends that have no state like that.

On my FreeBSD box (which doesn't have epoll(), so it's latch.c's old
school poll() for now), I see the connection proxy process eating a
lot of CPU and the temperature rising.  I see with truss that it's
doing this as fast as it can:

poll({ 13/POLLIN 17/POLLIN|POLLOUT },2,1000)     = 1 (0x1)

Ouch.  I admit that I had the idea to test on FreeBSD because I
noticed the patch introduces EPOLLET and I figured this might have
been tested only on Linux.  FWIW the same happens on a Mac.

That's all I had time for today, but I'm planning to poke this some
more, and get a better understand of how this works at an OS level.  I
can see fd passing, IO multiplexing, and other interesting things
happening.  I suspect there are many people on this list who have
thoughts about the architecture we should use to allow a smaller
number of PGPROCs and a larger number of connections, with various
different motivations.

> Thank you, I will look at Takeshi Ideriha's patch.

Cool.

> Sorry, I do not have access to Windows host, so can not check Win32

  C:\projects\postgresql\src\include\../interfaces/libpq/libpq-int.h(33):
fatal error C1083: Cannot open include file: 'pthread-win32.h': No
such file or directory (src/backend/postmaster/proxy.c)
[C:\projects\postgresql\postgres.vcxproj]

These relative includes in proxy.c are part of the problem:

#include "../interfaces/libpq/libpq-fe.h"
#include "../interfaces/libpq/libpq-int.h"

I didn't dig into this much but some first reactions:

1.  I see that proxy.c uses libpq, and correctly loads it as a dynamic
library just like postgres_fdw.  Unfortunately it's part of core, so
it can't use the same technique as postgres_fdw to add the libpq
headers to the include path.

2.  libpq-int.h isn't supposed to be included by code outside libpq,
and in this case it fails to find pthead-win32.h which is apparently
expects to find in either the same directory or the include path.  I
didn't look into what exactly is going on (I don't have Windows
either) but I think we can say the root problem is that you shouldn't
be including that from backend code.

-- 
Thomas Munro
https://enterprisedb.com

---

From: Konstantin Knizhnik <[email-masked]>
Date: Sun, 14 Jul 2019 22:56:21 +0300

> port->gss->enc.  I rebuilt without --with-gssapi to get past that.

First of all a lot of thanks for your review.

Sorry, I failed to reproduce the problem with GSSAPI.
I have configured postgres with --with-openssl --with-gssapi
and then try to connect to the serverwith psql using the following 
connection string:

psql "sslmode=require dbname=postgres port=6543 krbsrvname=POSTGRES"

There are no SIGFAULS and port->gss structure is normally initialized.

Can you please explain me more precisely how to reproduce the problem 
(how to configure postgres and how to connect to it)?

> backends that have no state like that.
That was not actually my idea: it was proposed by Dimitri Fontaine.
In PgPRO-EE we have another version of builtin connection pooler
which maintains session context and allows to use GUCs, prepared statements
and temporary tables in pooled sessions.
But the main idea of this patch was to make connection pooler less 
invasive and
minimize changes in Postgres core. This is why I have implemented proxy.

> been tested only on Linux.  FWIW the same happens on a Mac.

Yehh.
This is really the problem. In addition to FreeBSD and MacOS, it also 
takes place at Win32.
I have to think more how to solve it. We should somehow emulate 
"edge-triggered" more for this system.
The source of the problem is that proxy is reading data from one socket 
and writing it in another socket.
If write socket is busy, we have to wait until is is available. But at 
the same time there can be data available for input,
so poll will return immediately unless we remove read event for this 
socket. Not here how to better do it without changing
WaitEvenSet API.

> [C:\projects\postgresql\postgres.vcxproj]

I will investigate the problem with Win32 build once I get image of 
Win32 for VirtualBox.

> I didn't dig into this much but some first reactions:
I have added
override CPPFLAGS :=  $(CPPFLAGS) -I$(top_builddir)/src/port 
-I$(top_srcdir)/src/port

in Makefile for postmaster in order to fix this problem (as in 
interface/libpq/Makefile).
But looks like it is not enough. As I wrote above I will try to solve 
this problem once I get access to Win32 environment.

> be including that from backend code.
Looks like proxy.c has to be moved somewhere outside core?
May be make it an extension? But it may be not so easy to implement because
proxy has to be tightly integrated with postmaster.

---

From: Thomas Munro <[email-masked]>
Date: Mon, 15 Jul 2019 10:48:13 +1200

> (how to configure postgres and how to connect to it)?

Maybe it's just that postmaster.c's ConnCreate() always allocates a
struct for port->gss if the feature is enabled, but the equivalent
code in proxy.c's proxy_loop() doesn't?

./configure
  --prefix=$HOME/install/postgres \
  --enable-cassert \
  --enable-debug \
  --enable-depend \
  --with-gssapi \
  --with-icu \
  --with-pam \
  --with-ldap \
  --with-openssl \
  --enable-tap-tests \
  --with-includes="/opt/local/include" \
  --with-libraries="/opt/local/lib" \
  CC="ccache cc" CFLAGS="-O0"

~/install/postgres/bin/psql postgres -h localhost -p 6543

2019-07-15 08:37:25.348 NZST [97972] LOG:  server process (PID 97974)
was terminated by signal 11: Segmentation fault: 11

(lldb) bt
* thread #1, stop reason = signal SIGSTOP
  * frame #0: 0x0000000104163e7e
postgres`secure_read(port=0x00007fda9ef001d0, ptr=0x00000001047ab690,
len=8192) at be-secure.c:164:6
    frame #1: 0x000000010417760d postgres`pq_recvbuf at pqcomm.c:969:7
    frame #2: 0x00000001041779ed postgres`pq_getbytes(s="??\x04~?,
len=1) at pqcomm.c:1110:8
    frame #3: 0x0000000104284147
postgres`ProcessStartupPacket(port=0x00007fda9ef001d0,
secure_done=true) at postmaster.c:2064:6
...
(lldb) f 0
frame #0: 0x0000000104163e7e
postgres`secure_read(port=0x00007fda9ef001d0, ptr=0x00000001047ab690,
len=8192) at be-secure.c:164:6
   161         else
   162     #endif
   163     #ifdef ENABLE_GSS
-> 164         if (port->gss->enc)
   165         {
   166             n = be_gssapi_read(port, ptr, len);
   167             waitfor = WL_SOCKET_READABLE;
(lldb) print port->gss
(pg_gssinfo *) $0 = 0x0000000000000000

> and temporary tables in pooled sessions.

Interesting.  Do you serialise/deserialise plans and GUCs using
machinery similar to parallel query, and did you changed temporary
tables to use shared buffers?  People have suggested that we do that
to allow temporary tables in parallel queries too.  FWIW I have also
wondered about per (database, user) pools for reusable parallel
workers.

> minimize changes in Postgres core. This is why I have implemented proxy.

How do you do it without a proxy?

One idea I've wondered about that doesn't involve feeding all network
IO through an extra process and extra layer of syscalls like this is
to figure out how to give back your PGPROC slot when idle.  If you
don't have one and can't acquire one at the beginning of a
transaction, you wait until one becomes free.  When idle and not in a
transaction you give it back to the pool, perhaps after a slight
delay.  That may be impossible for some reason or other, I don't know.
If it could be done, it'd deal with the size-of-procarray problem
(since we like to scan it) and provide a kind of 'admission control'
(limiting number of transactions that can run), but wouldn't deal with
the amount-of-backend-memory-wasted-on-per-process-caches problem
(maybe solvable by shared caching).

Ok, time for a little bit more testing.  I was curious about the user
experience when there are no free backends.

1.  I tested with connection_proxies=1, max_connections=4, and I began
3 transactions.  Then I tried to make a 4th connection, and it blocked
while trying to connect and the log shows a 'sorry, too many clients
already' message.  Then I committed one of my transactions and the 4th
connection was allowed to proceed.

2.  I tried again, this time with 4 already existing connections and
no transactions.  I began 3 concurrent transactions, and then when I
tried to begin a 4th transaction the BEGIN command blocked until one
of the other transactions committed.

Some thoughts:   Why should case 1 block?  Shouldn't I be allowed to
connect, even though I can't begin a transaction without waiting yet?
 Why can I run only 3 transactions when I said max_connection=4?  Ah,
that's probably because the proxy itself is eating one slot, and
indeed if I set connection_proxies to 2 I can now run only two
concurrent transactions.  And yet when there were no transactions
running I could still open 4 connections.  Hmm.

The general behaviour of waiting instead of raising an error seems
sensible, and that's how client-side connection pools usually work.
Perhaps some of the people who have wanted admission control were
thinking of doing it at the level of queries rather than whole
transactions though, I don't know.  I suppose in extreme cases it's
possible to create invisible deadlocks, if a client is trying to
control more than one transaction concurrently, but that doesn't seem
like a real problem.

> socket. Not here how to better do it without changing

Can't you do this by removing events you're not interested in right
now, using ModifyWaitEvent() to change between WL_SOCKET_WRITEABLE and
WL_SOCKET_READABLE as appropriate?  Perhaps the problem you're worried
about is that this generates extra system calls in the epoll()
implementation?  I think that's not a problem for poll(), and could be
fixed for the kqueue() implementation I plan to commit eventually.  I
have no clue for Windows.

> proxy has to be tightly integrated with postmaster.

I'm not sure.  Seems like it should be solvable with the code in core.

-- 
Thomas Munro
https://enterprisedb.com

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 15 Jul 2019 10:09:42 +0300

> (pg_gssinfo *) $0 = 0x0000000000000000

Thank you, fixed (pushed to 
https://github.com/postgrespro/postgresql.builtin_pool.git repository).
I am not sure that GSS authentication works as intended, but at least

is normally connected.

> wondered about per (database, user) pools for reusable parallel

No. The main difference between PG-Pro (conn_pool) and vanilla 
(conn_proxy) version of connection pooler
is that first one  bind sessions to pool workers while last one is using 
proxy to scatter requests between workers.

So in conn_pool postmaster accepts client connection and the schedule it 
(using one of provided scheduling policies, i.e. round robin, random,
load balancing,...) to one of worker backends. Then client socket is 
transferred to this backend and client and backend are connected directly.
Session is never rescheduled, i.e. it is bounded to backend. One backend 
is serving multiple sessions. Sessions GUCs and some static variables
are saved in session context. Each session has its own temporary 
namespace, so temporary tables of different sessions do not interleave.

Direct connection of client and backend allows to eliminate proxy 
overhead. But at the same time - binding session to backend it is the 
main drawback of this approach. Long living transaction can block all 
other sessions scheduled to this backend.
I have though a lot about possibility to reschedule sessions. The main 
"show stopper" is actually temporary tables.
Implementation of temporary tables is one of the "bad smelling" places 
in Postgres causing multiple problems:
parallel queries, using temporary table at replica, catalog bloating, 
connection pooling...
This is why I have tried to implement "global" temporary tables (like in 
Oracle).
I am going to publish this patch soon: in this case table definition is 
global, but data is local for each session.
Also global temporary tables are accessed through shared pool which 
makes it possible to use them in parallel queries.
But it is separate story, not currently related with connection pooling.

Approach with proxy doesn't suffer from this problem.

> How do you do it without a proxy?

I hope I have explained it above.
Actually this version pf connection pooler is also available at github 
https://github.com/postgrespro/postgresql.builtin_pool.git repository
branch conn_pool).

> running I could still open 4 connections.  Hmm.

max_connections is not the right switch to control behavior of 
connection pooler.
You should adjust session_pool_size, connection_proxies and max_sessions 
parameters.

What happen in 1) case? Default value of session_pool_size is 10. It 
means that postgres will spawn up to 10 backens for each database/user 
combination. But max_connection limit will exhausted earlier. May be it 
is better to prohibit setting session_pool_size larger than max_connection
or automatically adjust it according to max_connections. But it is also 
no so easy to enforce, because separate set of pool workers is created for
each database/user combination.

So I agree that observer behavior is confusing, but I do not have good 
idea how to improve it.

> have no clue for Windows.
Window implementation is similar with poll().
Yes, definitely it can be done by removing read handle from wait even 
set after each pending write operation.
But it seems to be very inefficient in case of epoll() implementation 
(where changing event set requires separate syscall).
So either we have to add some extra function, i.e. WaitEventEdgeTrigger 
which will do nothing for epoll(),
either somehow implement edge triggering inside WaitEvent* 
implementation itself (not clear how to do it, since read/write 
operations are
not performed through this API).

> I'm not sure.  Seems like it should be solvable with the code in core.
I also think so. It is now working at Unix and I hope I can also fix 
Win32 build.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 15 Jul 2019 17:04:47 +0300

> been tested only on Linux.  FWIW the same happens on a Mac.
I have committed patch which emulates epoll EPOLLET flag and so should 
avoid busy loop with poll().
I will be pleased if you can check it at FreeBSD  box.

 
 
  </part>

 

+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
+/*
+ * StartProxyWorker

 

index 0000000000..36f1a53987
@@ -0,0 +1,1046 @@
+	bool     write_pending;     /* emulate epoll EPOLLET (edge-triggered) flag */
+	else if (rc < 0) /* do not accept more read events while write requests is pending */
+		ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_WRITEABLE|WL_SOCKET_EDGE, NULL);
+		chan->write_pending = true;
+	else if (chan->write_pending && rc > 0)
+		ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_READABLE|WL_SOCKET_WRITEABLE|WL_SOCKET_EDGE, NULL);
+		chan->write_pending = false;
+#if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
+		free(port->gss);
+#if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
+					port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
+					if (!port->gss)

 	/*
index 2426cbcf8e..d2806b7399 100644
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*
@@ -767,10 +797,16 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 {
 	WaitEvent  *event;

 
+#if defined(WAIT_USE_EPOLL)
+	/* ModifyWaitEvent is used to emulate epoll EPOLLET (edge-triggered) flag */
+	if (events & WL_SOCKET_EDGE)
+		return;
+#endif
+
 	/*
 	 * If neither the event mask nor the associated latch changes, return
 	 * early. That's an important optimization for some sockets, where
@@ -804,9 +840,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 #if defined(WAIT_USE_EPOLL)
 	WaitEventAdjustEpoll(set, event, EPOLL_CTL_MOD);
 #elif defined(WAIT_USE_POLL)
-	WaitEventAdjustPoll(set, event);
+	WaitEventAdjustPoll(set, event, false);
 #elif defined(WAIT_USE_WIN32)
-	WaitEventAdjustWin32(set, event);
+	WaitEventAdjustWin32(set, event, false);
 #endif
 }
 
@@ -844,6 +880,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -852,21 +890,39 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;
@@ -897,9 +953,25 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -912,7 +984,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
@@ -929,8 +1001,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 
@@ -1336,7 +1408,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,

 

 
+	{
 
+	{
 
+	{
 
+	{
 
 	switch (stmt->kind)
 	{

 

 
 #endif							/* FRONTEND */

 

 typedef struct WaitEvent

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 16 Jul 2019 09:19:47 +0300

> I will be pleased if you can check it at FreeBSD  box.
Sorry, attached patch was incomplete.
Please try this version of the patch.

 
 
  </part>

 

+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
+/*
+ * StartProxyWorker

 

index 0000000000..1531bd7554
@@ -0,0 +1,1061 @@
+	bool     write_pending;      /* write request is pending: emulate epoll EPOLLET (edge-triggered) flag */
+	bool     read_pending;       /* read request is pending: emulate epoll EPOLLET (edge-triggered) flag */
+	else if (rc < 0)
+		/* do not accept more read events while write request is pending */
+	else if (chan->write_pending)
+		/* resume accepting read events */
+		ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_READABLE|WL_SOCKET_EDGE, NULL);
+				/* do not accept more write events while read request is pending */
+				ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_READABLE|WL_SOCKET_EDGE, NULL);
+				chan->read_pending = true;
+		else if (chan->read_pending)
+			/* resume accepting all events */
+			chan->read_pending = false;

 	/*
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 

 
 
+	{
 
+	{
 
+	{
 
+	{
 
 	switch (stmt->kind)
 	{

 

 
 #endif							/* FRONTEND */

 

 typedef struct WaitEvent

---

From: Ryan Lambert <[email-masked]>
Date: Wed, 17 Jul 2019 21:01:40 -0600

Hi Konstantin,

Thanks for your work on this.  I'll try to do more testing in the next few
days, here's what I have so far.

make installcheck-world: passed

The v8 patch [1] applies, though I get indent and whitespace errors:

<stdin>:79: tab in indent.
                 "Each proxy launches its own subset of backends. So
maximal number of non-tainted backends is "
<stdin>:80: tab in indent.
                  "session_pool_size*connection_proxies*databases*roles.
<stdin>:519: indent with spaces.
    char buf[CMSG_SPACE(sizeof(sock))];
<stdin>:520: indent with spaces.
    memset(buf, '\0', sizeof(buf));
<stdin>:522: indent with spaces.
    /* On Mac OS X, the struct iovec is needed, even if it points to
minimal data */
warning: squelched 82 whitespace errors
warning: 87 lines add whitespace errors.

In connpool.sgml:

"but it can be changed to standard Postgres 4321"

Should be 5432?

" As far as pooled backends are not terminated on client exist, it will not
    be possible to drop database to which them are connected."

Active discussion in [2] might change that, it is also in this July
commitfest [3].

"Unlike pgbouncer and other external connection poolera"

Should be "poolers"

"So developers of client applications still have a choice
    either to avoid using session-specific operations either not to use
pooling."

That sentence isn't smooth for me to read.  Maybe something like:
"Developers of client applications have the choice to either avoid using
session-specific operations, or not use built-in pooling."

[1]
https://www.postgresql.org/message-id/attachment/102610/builtin_connection_proxy-8.patch

[2]
https://www.postgresql.org/message-id/flat/CAP_rwwmLJJbn70vLOZFpxGw3XD7nLB_7%2BNKz46H5EOO2k5H7OQ%40mail.gmail.com

[3] https://commitfest.postgresql.org/23/2055/

Ryan Lambert

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 18 Jul 2019 15:10:35 +0300

Hi, Ryan

On 18.07.2019 6:01, Ryan Lambert wrote:
> Hi Konstantin,
>
> Thanks for your work on this.  I'll try to do more testing in the next 
> few days, here's what I have so far.
>
>                      "Each proxy launches its own subset of backends.
>     So maximal number of non-tainted backends is "
>         /* On Mac OS X, the struct iovec is needed, even if it points
>     to minimal data */
>     either to avoid using session-specific operations either not to 
> use pooling."
>
> "Developers of client applications have the choice to either avoid 
> using session-specific operations, or not use built-in pooling."
>
>
> [1] 

Thank you for review.
I have fixed all reported issues except one related with "dropdb 
--force" discussion.
As far as this patch is not yet committed, I can not rely on it yet.
Certainly I can just remove this sentence from documentation, assuming 
that this patch will be committed soon.
But then some extra efforts will be needed to terminated pooler backends 
of dropped database.

index 84341a30e5..50be793e26 100644
 
+          Postmaster spawns separate worker process for each proxy. Postmaster scatters connections between proxies using one of scheduling policies (round-robin, random, load-balancing).
+		  Each proxy launches its own subset of backends.
+          So maximal number of non-tainted backends is  <varname>session_pool_size*connection_proxies*databases*roles</varname>.
index 0000000000..8486ce1e8d
+    Default value is 6543, but it can be changed to standard Postgres 5432, so by default all connections to the databases will be pooled.
+    Unlike pgbouncer and other external connection poolers, built-in connection pooler doesn't require installation and configuration of some other components.
+    Although it is not so difficult to do, but it requires more changes in Postgres core. Developers of client applications have
+    the choice to either avoid using session-specific operations, or not use built-in pooling. For example, using prepared statements can improve speed of simple queries

  </part>

 

+	if (FeBeWaitSet)
 
+

 
 
index 0000000000..a76db8d171

 

 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
+/*
+ * StartProxyWorker

 

 
 
 	/*
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 

 
 
+	{
 
+	{
 
+	{
 
+	{
 
 	switch (stmt->kind)
 	{

 

 
 #endif							/* FRONTEND */

 

 typedef struct WaitEvent

---

From: Ryan Lambert <[email-masked]>
Date: Thu, 18 Jul 2019 07:07:53 -0600

> I have fixed all reported issues except one related with "dropdb --force"
> discussion.

Great, thanks.  Understood about the non-committed item.  I did mark that
item as ready for committer last night so we will see.  I should have time
to put the actual functionality of your patch to test later today or
tomorrow.  Thanks,

Ryan Lambert

---

From: Ryan Lambert <[email-masked]>
Date: Thu, 18 Jul 2019 21:36:48 -0600

Here's what I found tonight in your latest patch (9).  The output from git
apply is better, fewer whitespace errors, but still getting the following.
Ubuntu 18.04 if that helps.

git apply -p1 < builtin_connection_proxy-9.patch
<stdin>:79: tab in indent.
                  Each proxy launches its own subset of backends.
<stdin>:634: indent with spaces.
    union {
<stdin>:635: indent with spaces.
       struct sockaddr_in inaddr;
<stdin>:636: indent with spaces.
       struct sockaddr addr;
<stdin>:637: indent with spaces.
    } a;
warning: squelched 54 whitespace errors
warning: 59 lines add whitespace errors.

A few more minor edits.  In config.sgml:

"If the <varname>max_sessions</varname> limit is reached new connection are
not accepted."
Should be "connections".

"The default value is 10, so up to 10 backends will server each database,"
"sever" should be "serve" and the sentence should end with a period instead
of a comma.

In postmaster.c:

/* The socket number we are listening for poolled connections on */
"poolled" --> "pooled"

"(errmsg("could not create listen socket for locahost")));"

"locahost" -> "localhost".

" * so to support order balancing we should do dome smart work here."

"dome" should be "some"?

I don't see any tests covering this new functionality.  It seems that this
is significant enough functionality to warrant some sort of tests, but I
don't know exactly what those would/should be.

Thanks,
Ryan

---

From: Konstantin Knizhnik <[email-masked]>
Date: Sat, 20 Jul 2019 00:10:34 +0300

On 19.07.2019 6:36, Ryan Lambert wrote:
> Here's what I found tonight in your latest patch (9).  The output from 
> git apply is better, fewer whitespace errors, but still getting the 
> following.  Ubuntu 18.04 if that helps.
>
> "If the <varname>max_sessions</varname> limit is reached new 
> connection are not accepted."
> Should be "connections".
>
> "sever" should be "serve" and the sentence should end with a period 
> instead of a comma.
>
>
> In postmaster.c:
>
> I don't see any tests covering this new functionality.  It seems that 
> this is significant enough functionality to warrant some sort of 
> tests, but I don't know exactly what those would/should be.
>

Thank you once again for this fixes.
Updated patch is attached.

Concerning testing: I do not think that connection pooler needs some 
kind of special tests.
The idea of built-in connection pooler is that it should be able to 
handle all requests normal postgres can do.
I have added to regression tests extra path with enabled connection proxies.
Unfortunately, pg_regress is altering some session variables, so it 
backend becomes tainted and so
pooling is not actually used (but communication through proxy is tested).

It is  also possible to run pg_bench with different number of 
connections though connection pooler.

index 84341a30e5..f8b93f16ed 100644
 
+          If the <varname>max_sessions</varname> limit is reached new connections are not accepted.
+          The default value is 10, so up to 10 backends will serve each database,

  </part>

 

+	if (FeBeWaitSet)
 
+

 
 
index d5b5e771e9..1564c8c611 100644

index 688ad439ed..57d856fd64 100644
 
+/* The socket number we are listening for pooled connections on */
+int			ProxyPortNumber;
+
 /* The directory names for Unix socket(s) */
 char	   *Unix_socket_directories;

 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 
 
+					(errmsg("could not create listen socket for localhost")));

 	/*
 
+/**
+ * so to support order balancing we should do some smart work here.
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
+/*
+ * StartProxyWorker

 

index 0000000000..6314f1eb8d
@@ -0,0 +1,1073 @@
+static Channel* backend_start(SessionPool* pool);
+backend_reschedule(Channel* chan, bool is_new)
+	if (is_new || !chan->backend_proc->is_tainted) /* If backend is not storing some session context */
+		ELOG(LOG, "Backed %d is tainted", chan->backend_pid);
+			idle_backend = backend_start(chan->pool);
+			backend_reschedule(peer, false);
+			backend_reschedule(peer, false);
+			return backend_reschedule(chan, false);
+backend_start(SessionPool* pool)
+		if (chan->pool->pending_clients)
+			/* Try to start new backend instead of terminated */
+			Channel* new_backend = backend_start(chan->pool);
+			if (new_backend != NULL)
+				ELOG(LOG, "Spawn new backend %p instead of terminated %p", new_backend, chan);
+				backend_reschedule(new_backend, true);

 	/*
 
 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 

 
 
+	{
 
+	{
 
+	{
 
+	{
 
 	switch (stmt->kind)
 	{

 

 
 #endif							/* FRONTEND */

 

 typedef struct WaitEvent

diff --git a/src/test/regress/GNUmakefile b/src/test/regress/GNUmakefile
index a24cfd4e01..38dda4dfe5 100644
--- a/src/test/regress/GNUmakefile
+++ b/src/test/regress/GNUmakefile
@@ -130,6 +130,7 @@ REGRESS_OPTS = --dlpath=. --max-concurrent-tests=20 $(EXTRA_REGRESS_OPTS)
 
 check: all tablespace-setup
 	$(pg_regress_check) $(REGRESS_OPTS) --schedule=$(srcdir)/parallel_schedule $(MAXCONNOPT) $(EXTRA_TESTS)
+	$(pg_regress_check) $(REGRESS_OPTS) --schedule=$(srcdir)/parallel_schedule $(MAXCONNOPT) $(EXTRA_TESTS) --port=6543 --temp-config=$(srcdir)/conn_proxy.conf
 
 check-tests: all tablespace-setup | temp-install
 	$(pg_regress_check) $(REGRESS_OPTS) $(MAXCONNOPT) $(TESTS) $(EXTRA_TESTS)
diff --git a/src/test/regress/conn_proxy.conf b/src/test/regress/conn_proxy.conf
new file mode 100644
index 0000000000..ebaa257f4b
--- /dev/null
+++ b/src/test/regress/conn_proxy.conf
@@ -0,0 +1,3 @@
+connection_proxies = 1
+port = 5432
+log_statement=all

---

From: Ryan Lambert <[email-masked]>
Date: Wed, 24 Jul 2019 15:58:27 -0600

Hello Konstantin,

> Concerning testing: I do not think that connection pooler needs some kind
of special tests.
> Thank you for your work on this patch, I took some good time to really
explore the configuration and do some testing with pgbench.  This round of
testing was done against patch 10 [1] and master branch commit a0555ddab9
from 7/22.

Thank you for explaining, I wasn't sure.

make installcheck-world: tested, passed
Implements feature:  tested, passed
Documentation:  I need to review again, I saw typos when testing but didn't
make note of the details.

Applying the patch [1] has improved from v9, still getting these:

git apply -p1 < builtin_connection_proxy-10.patch
<stdin>:1536: indent with spaces.
            /* Has pending clients: serve one of them */
<stdin>:1936: indent with spaces.
                        /* If we attach new client to the existed backend,
then we need to send handshake response to the client */
<stdin>:2208: indent with spaces.
                            if (port->sock == PGINVALID_SOCKET)
<stdin>:2416: indent with spaces.
    FuncCallContext* srf_ctx;
<stdin>:2429: indent with spaces.
        ps_ctx = (PoolerStateContext*)palloc(sizeof(PoolerStateContext));
warning: squelched 5 whitespace errors
warning: 10 lines add whitespace errors.

I used a DigitalOcean droplet with 2 CPU and 2 GB RAM and SSD for this
testing, Ubuntu 18.04.  I chose the smaller server size based on the
availability of similar and recent results around connection pooling [2]
that used AWS EC2 m4.large instance (2 cores, 8 GB RAM) and pgbouncer.
Your prior pgbench tests [3] also focused on larger servers so I wanted to
see how this works on smaller hardware.

Considering this from connpool.sgml:
"<varname>connection_proxies</varname> specifies number of connection proxy
processes which will be spawned. Default value is zero, so connection
pooling is disabled by default."

That hints to me that connection_proxies is the main configuration to start
with so that was the only configuration I changed from the default for this
feature.  I adjusted shared_buffers to 500MB (25% of total) and
max_connections to 1000.  Only having one proxy gives subpar performance
across the board, so did setting this value to 10.  My hunch is this value
should roughly follow the # of cpus available, but that's just a hunch.

I tested with 25, 75, 150, 300 and 600 connections.  Initialized with a
scale of 1000 and ran read-only tests.  Basic pgbench commands look like
the following, I have full commands and results from 18 tests included in
the attached MD file.  Postgres was restarted between each test.

pgbench -i -s 1000 bench_test
pgbench -p 6543 -c 300 -j 2 -T 600 -P 60 -S bench_test

Tests were all ran from the same server.  I intend to do further testing
with external connections using SSL.

General observations:
For each value of connection_proxies, the TPS observed at 25 connections
held up reliably through 600 connections. For this server using
connection_proxies = 2 was the fastest, but setting to 1 or 10 still
provided **predictable** throughput.  That seems to be a good attribute for
this feature.

Also predictable was the latency increase, doubling the connections roughly
doubles the latency.  This was true with or without connection pooling.

Focusing on disabled connection pooling vs the feature with two proxies,
the results are promising, the breakpoint seems to be around 150
connections.

Low connections (25):  -15% TPS; +45% latency
Medium connections (300):  +21% TPS; +38% latency
High connections (600):  Couldn't run without pooling... aka: Win for
pooling!

The two attached charts show the TPS and average latency of these two
scenarios.  This feature does a great job of maintaining a consistent TPS
as connection numbers increase.  This comes with tradeoffs of lower
throughput with < 150 connections, and higher latency across the board.
The increase in latency seems reasonable to me based on the testing I have
done so far. Compared to the results from [2] it seems latency is affecting
this feature a bit more than it does pgbouncer, yet not unreasonably so
given the benefit of having the feature built in and the reduced complexity.

I don't understand yet how max_sessions ties in.
Also, having both session_pool_size and connection_proxies seemed confusing
at first.  I still haven't figured out exactly how they relate together in
the overall operation and their impact on performance.  The new view
helped, I get the concept of **what** it is doing (connection_proxies =
more rows, session_pool_size = n_backends for each row), it's more a lack
of understanding the **why** regarding how it will operate.

postgres=# select * from pg_pooler_state();
 pid  | n_clients | n_ssl_clients | n_pools | n_backends |
n_dedicated_backends | tx_bytes  | rx_bytes  | n_transactions
------+-----------+---------------+---------+------------+----------------------+-----------+-----------+----------------
 1682 |        75 |             0 |       1 |         10 |
   0 | 366810458 | 353181393 |        5557109
 1683 |        75 |             0 |       1 |         10 |
   0 | 368464689 | 354778709 |        5582174
(2 rows

I am not sure how I feel about this:
"Non-tainted backends are not terminated even if there are no more
connected sessions."

Would it be possible (eventually) to monitor connection rates and free up
non-tainted backends after a time?  The way I'd like to think of that
working would be:

If 50% of backends are unused for more than 1 hour, release 10% of
established backends.

The two percentages and time frame would ideally be configurable, but setup
in a way that it doesn't let go of connections too quickly, causing
unnecessary expense of re-establishing those connections.  My thought is if
there's one big surge of connections followed by a long period of lower
connections, does it make sense to keep those extra backends established?

I'll give the documentation another pass soon.  Thanks for all your work on
this, I like what I'm seeing so far!

[1]
https://www.postgresql.org/message-id/attachment/102732/builtin_connection_proxy-10.patch
[2] http://richyen.com/postgres/2019/06/25/pools_arent_just_for_cars.html
[3]
https://www.postgresql.org/message-id/ede4470a-055b-1389-0bbd-840f0594b758%40postgrespro.ru

Thanks,
Ryan Lambert

On Fri, Jul 19, 2019 at 3:10 PM Konstantin Knizhnik <
[email-masked]> wrote:

> "If the <varname>max_sessions</varname> limit is reached new connection
> are not accepted."
> Should be "connections".
>
> Concerning testing: I do not think that connection pooler needs some kind
> of special tests.
> The idea of built-in connection pooler is that it should be able to handle
> all requests normal postgres can do.
> It is  also possible to run pg_bench with different number of connections
> though connection pooler.
>
>
> Thanks,
> Ryan
>
>
>

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 25 Jul 2019 15:00:30 +0300

Hello Ryan,

Thank you very much for review and benchmarking.
My answers are inside.

> Applying the patch [1] has improved from v9, still getting these:
Fixed.

>  used a DigitalOcean droplet with 2 CPU and 2 GB RAM and SSD for this 
> availability of similar and recent results around connection pooling 
> [2] that used AWS EC2 m4.large instance (2 cores, 8 GB RAM) and 
> pgbouncer.  Your prior pgbench tests [3] also focused on larger 
> servers so I wanted to see how this works on smaller hardware.
>
> "<varname>connection_proxies</varname> specifies number of connection 
> proxy processes which will be spawned. Default value is zero, so 
> connection pooling is disabled by default."
>
> That hints to me that connection_proxies is the main configuration to 
> start with so that was the only configuration I changed from the 
> default for this feature.  I adjusted shared_buffers to 500MB (25% of 
> total) and max_connections to 1000.  Only having one proxy gives 
> subpar performance across the board, so did setting this value to 10.  
> My hunch is this value should roughly follow the # of cpus available, 
> but that's just a hunch.
>

I do not think that number of proxies should depend on number of CPUs. 
Proxy process is not performing any computations, it is just redirecting 
data from client to backend and visa versa.
Certainly starting  form some number of connections is becomes 
bottleneck. The same is true for pgbouncer: you need to start several 
pgbouncer instances to be able to utilize all resources and provide best 
performance at
computer with large number of cores. The optimal value greatly depends 
on number on workload, it is difficult to suggest some formula which 
allows to calculate optimal number of proxies for each configuration.
> Also, having both session_pool_size and connection_proxies seemed 
> confusing at first.  I still haven't figured out exactly how they 
> relate together in the overall operation and their impact on performance.

"max_sessions" is mostly technical parameter. To listen client 
connections I need to initialize WaitEvent set specdify maximal number 
of events.
It should not somehow affect performance. So just  specifying large 
enough value should work in most cases.
But I do not want to hardcode some constants and that it why I add GUC 
variable.

"connections_proxies" is used mostly to toggle connection pooling.
Using more than 1 proxy is be needed only for huge workloads (hundreds 
connections).

And "session_pool_size" is core parameter  which determine efficiency of 
pooling.
The main trouble with it now, is that it is per database/user 
combination. Each such combination will have its own connection pool.
Choosing optimal value of pooler backends is non-trivial task. It 
certainly depends on number of available CPU cores.
But if backends and mostly disk-bounded, then optimal number of pooler 
worker can be large than number of cores.
Presence of several pools make this choice even more complicated.

> The new view helped, I get the concept of **what** it is doing 
> (connection_proxies = more rows, session_pool_size = n_backends for 
> each row), it's more a lack of understanding the **why** regarding how 
> it will operate.
>
>
PgPRO EE version of connection pooler has "idle_pool_worker_timeout" 
parameter which allows to terminate idle workers.
It is possible to implement it also for vanilla version of pooler. But 
primary intention of this patch was to minimize changes in Postgres core

>
> Would it be possible (eventually) to monitor connection rates and free 
> up non-tainted backends after a time?  The way I'd like to think of 
> that working would be:
>

>
> The two percentages and time frame would ideally be configurable, but 
> setup in a way that it doesn't let go of connections too quickly, 
> causing unnecessary expense of re-establishing those connections.  My 
> thought is if there's one big surge of connections followed by a long 
> period of lower connections, does it make sense to keep those extra 
> backends established?
>

I think that idle timeout is enough but more complicated logic can also 
be implemented.

>
> I'll give the documentation another pass soon.  Thanks for all your 
> work on this, I like what I'm seeing so far!
>
Thank you very much.
I attached new version of the patch with fixed indentation problems and 
Win32 specific fixes.

index 84341a3..f8b93f1 100644
 
index 0000000..8486ce1
index 8960f112..5b19fef 100644
 
index 3e115f1..029f0dc 100644
 
  </part>
 
index c278ee7..acbaed3 100644
 
index fd67d2a..10a14d0 100644
 
index 384887e..ebff20a 100644

+	if (FeBeWaitSet)
 
+

 
 
index 0000000..a76db8d
index d5b5e77..1564c8c 100644

index 0000000..de787ba
@@ -0,0 +1,46 @@
index 688ad43..57d856f 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
@@ -5526,6 +5710,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker

 

index 0000000..f5de1f0
@@ -0,0 +1,1078 @@
+		/* Do not try to read more data if edge-triggered mode is not supported */
+		if (!WaitEventUseEpoll)
+		closesocket(chan->backend_socket);
+		closesocket(port->sock);
+		closesocket(chan->client_port->sock);
+		closesocket(chan->backend_socket);
+					/* At systems not supporttring epoll edge triggering (Win32, FreeBSD, MacOS), we need to disable writable event to avoid busy loop */
+					ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_READABLE | WL_SOCKET_EDGE, NULL);
index d7d7335..6d32d8f 100644

 	/*
 	 * Set up other modules that need some shared memory space
diff --git a/src/backend/storage/ipc/latch.c b/src/backend/storage/ipc/latch.c
index 2426cbc..23e9706 100644
--- a/src/backend/storage/ipc/latch.c
+++ b/src/backend/storage/ipc/latch.c
@@ -72,11 +72,19 @@
 #error "no wait set implementation available"
 #endif
 
+#if defined(WAIT_USE_EPOLL)
+bool WaitEventUseEpoll = true;
+#else
+bool WaitEventUseEpoll = false;
+#endif
+
+
 /* typedef in latch.h */
 struct WaitEventSet
 {
 	int			nevents;		/* number of registered events */
 	int			nevents_space;	/* maximum number of events in this set */
+	int         free_events;    /* L1-list of free events linked by "pos" and terminated by -1*/
 
 	/*
@@ -137,9 +145,9 @@ static void drainSelfPipe(void);
 
 static inline int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
@@ -585,6 +593,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 	set->latch = NULL;
 	set->nevents_space = nevents;
 	set->exit_on_postmaster_death = false;
+	set->free_events = -1;
 
 #if defined(WAIT_USE_EPOLL)
 #ifdef EPOLL_CLOEXEC
@@ -691,9 +700,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -720,8 +731,19 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
@@ -748,15 +770,30 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
 /*
@@ -767,10 +804,16 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 {
 	WaitEvent  *event;

 
@@ -804,9 +847,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
@@ -844,6 +887,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -852,21 +897,39 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;
@@ -897,9 +960,25 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -912,7 +991,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
@@ -929,8 +1008,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 
@@ -1336,7 +1415,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
index 44a59e1..62ec2af 100644
 
index 3bf96de..79001cc 100644

index 92c4fee..47b3845 100644
 
@@ -550,7 +558,7 @@ int			huge_pages;
 
 /*
  * These variables are all dummies that don't do anything, except in some
- * cases provide the value for SHOW to display.  The real state is elsewhere
+ * cases provide the value for SHOW to display.	 The real state is elsewhere
  * and is kept in sync by assign_hooks.
  */
 static char *syslog_ident_str;
@@ -1166,7 +1174,7 @@ static struct config_bool ConfigureNamesBool[] =
 			gettext_noop("Writes full pages to WAL when first modified after a checkpoint."),
 			gettext_noop("A page write in process during an operating system crash might be "
 						 "only partially written to disk.  During recovery, the row changes "
-						 "stored in WAL are not enough to recover.  This option writes "
+						 "stored in WAL are not enough to recover.	This option writes "
 						 "pages when first modified after a checkpoint to WAL so full recovery "
 						 "is possible.")
 		},
@@ -1286,6 +1294,16 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
@@ -2138,6 +2156,42 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2185,6 +2239,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2254,7 +2318,7 @@ static struct config_int ConfigureNamesInt[] =
 
 	/*
 	 * We use the hopefully-safely-small value of 100kB as the compiled-in
-	 * default for max_stack_depth.  InitializeGUCOptions will increase it if
+	 * default for max_stack_depth.	 InitializeGUCOptions will increase it if
 	 * possible, depending on the actual platform-specific stack limit.
 	 */
 	{
@@ -4550,6 +4614,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -4561,7 +4635,7 @@ static struct config_enum ConfigureNamesEnum[] =
 
 /*
  * To allow continued support of obsolete names for GUC variables, we apply
- * the following mappings to any unrecognized name.  Note that an old name
+ * the following mappings to any unrecognized name.	 Note that an old name
  * should be mapped to a new one only if the new variable has very similar
  * semantics to the old.
  */
@@ -4747,7 +4821,7 @@ extra_field_used(struct config_generic *gconf, void *extra)
 }
 
 /*
- * Support for assigning to an "extra" field of a GUC item.  Free the prior
+ * Support for assigning to an "extra" field of a GUC item.	 Free the prior
  * value if it's not referenced anywhere else in the item (including stacked
  * states).
  */
@@ -4837,7 +4911,7 @@ get_guc_variables(void)

 /*
- * Build the sorted array.  This is split out so that it could be
+ * Build the sorted array.	This is split out so that it could be
  * re-executed after startup (e.g., we could allow loadable modules to
  * add vars, and then we'd need to re-sort).
  */
@@ -5011,7 +5085,7 @@ add_placeholder_variable(const char *name, int elevel)
 
 	/*
 	 * The char* is allocated at the end of the struct since we have no
-	 * 'static' place to point to.  Note that the current value, as well as
+	 * 'static' place to point to.	Note that the current value, as well as
 	 * the boot and reset values, start out NULL.
 	 */
 	var->variable = (char **) (var + 1);
@@ -5027,7 +5101,7 @@ add_placeholder_variable(const char *name, int elevel)
 }
 
 /*
- * Look up option NAME.  If it exists, return a pointer to its record,
+ * Look up option NAME.	 If it exists, return a pointer to its record,
  * else return NULL.  If create_placeholders is true, we'll create a
  * placeholder record for a valid-looking custom variable name.
  */
@@ -5053,7 +5127,7 @@ find_option(const char *name, bool create_placeholders, int elevel)
 		return *res;
 
 	/*
-	 * See if the name is an obsolete name for a variable.  We assume that the
+	 * See if the name is an obsolete name for a variable.	We assume that the
 	 * set of supported old names is short enough that a brute-force search is
 	 * the best way.
 	 */
@@ -5414,7 +5488,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	}
 
 	/*
-	 * Read the configuration file for the first time.  This time only the
+	 * Read the configuration file for the first time.	This time only the
 	 * data_directory parameter is picked up to determine the data directory,
 	 * so that we can read the PG_AUTOCONF_FILENAME file next time.
 	 */
@@ -5709,7 +5783,7 @@ AtStart_GUC(void)
 {
 	/*
 	 * The nest level should be 0 between transactions; if it isn't, somebody
-	 * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.  We
+	 * didn't call AtEOXact_GUC, or called it with the wrong nestLevel.	 We
 	 * throw a warning but make no other effort to clean up.
 	 */
 	if (GUCNestLevel != 0)
@@ -5733,10 +5807,10 @@ NewGUCNestLevel(void)
 /*
  * Do GUC processing at transaction or subtransaction commit or abort, or
  * when exiting a function that has proconfig settings, or when undoing a
- * transient assignment to some GUC variables.  (The name is thus a bit of
+ * transient assignment to some GUC variables.	(The name is thus a bit of
  * a misnomer; perhaps it should be ExitGUCNestLevel or some such.)
  * During abort, we discard all GUC settings that were applied at nesting
- * levels >= nestLevel.  nestLevel == 1 corresponds to the main transaction.
+ * levels >= nestLevel.	 nestLevel == 1 corresponds to the main transaction.
  */
 void
 AtEOXact_GUC(bool isCommit, int nestLevel)
@@ -6067,7 +6141,7 @@ ReportGUCOption(struct config_generic *record)
 
 /*
  * Convert a value from one of the human-friendly units ("kB", "min" etc.)
- * to the given base unit.  'value' and 'unit' are the input value and unit
+ * to the given base unit.	'value' and 'unit' are the input value and unit
  * to convert from (there can be trailing spaces in the unit string).
  * The converted value is stored in *base_value.
  * It's caller's responsibility to round off the converted value as necessary
@@ -6130,7 +6204,7 @@ convert_to_base_unit(double value, const char *unit,
  * Convert an integer value in some base unit to a human-friendly unit.
  *
  * The output unit is chosen so that it's the greatest unit that can represent
- * the value without loss.  For example, if the base unit is GUC_UNIT_KB, 1024
+ * the value without loss.	For example, if the base unit is GUC_UNIT_KB, 1024
  * is converted to 1 MB, but 1025 is represented as 1025 kB.
  */
 static void
@@ -6764,7 +6838,7 @@ set_config_option(const char *name, const char *value,
 
 	/*
 	 * GUC_ACTION_SAVE changes are acceptable during a parallel operation,
-	 * because the current worker will also pop the change.  We're probably
+	 * because the current worker will also pop the change.	 We're probably
 	 * dealing with a function having a proconfig entry.  Only the function's
 	 * body should observe the change, and peer workers do not share in the
 	 * execution of a function call started by this worker.
@@ -6806,7 +6880,7 @@ set_config_option(const char *name, const char *value,
 			{
 				/*
 				 * We are re-reading a PGC_POSTMASTER variable from
-				 * postgresql.conf.  We can't change the setting, so we should
+				 * postgresql.conf.	 We can't change the setting, so we should
 				 * give a warning if the DBA tries to change it.  However,
 				 * because of variant formats, canonicalization by check
 				 * hooks, etc, we can't just compare the given string directly
@@ -6868,7 +6942,7 @@ set_config_option(const char *name, const char *value,
 				 * non-default settings from the CONFIG_EXEC_PARAMS file
 				 * during backend start.  In that case we must accept
 				 * PGC_SIGHUP settings, so as to have the same value as if
-				 * we'd forked from the postmaster.  This can also happen when
+				 * we'd forked from the postmaster.	 This can also happen when
 				 * using RestoreGUCState() within a background worker that
 				 * needs to have the same settings as the user backend that
 				 * started it. is_reload will be true when either situation
@@ -6915,9 +6989,9 @@ set_config_option(const char *name, const char *value,
 	 * An exception might be made if the reset value is assumed to be "safe".
 	 *
 	 * Note: this flag is currently used for "session_authorization" and
-	 * "role".  We need to prohibit changing these inside a local userid
+	 * "role".	We need to prohibit changing these inside a local userid
 	 * context because when we exit it, GUC won't be notified, leaving things
-	 * out of sync.  (This could be fixed by forcing a new GUC nesting level,
+	 * out of sync.	 (This could be fixed by forcing a new GUC nesting level,
 	 * but that would change behavior in possibly-undesirable ways.)  Also, we
 	 * prohibit changing these in a security-restricted operation because
 	 * otherwise RESET could be used to regain the session user's privileges.
@@ -7490,7 +7564,7 @@ set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
  * Set a config option to the given value.
  *
  * See also set_config_option; this is just the wrapper to be called from
- * outside GUC.  (This function should be used when possible, because its API
+ * outside GUC.	 (This function should be used when possible, because its API
  * is more stable than set_config_option's.)
  *
  * Note: there is no support here for setting source file/line, as it
@@ -7696,7 +7770,7 @@ flatten_set_variable_args(const char *name, List *args)
 		Node	   *arg = (Node *) lfirst(l);
 		char	   *val;
 		TypeName   *typeName = NULL;
-		A_Const    *con;
+		A_Const	   *con;
 
 		if (l != list_head(args))
 			appendStringInfoString(&buf, ", ");
@@ -7753,7 +7827,7 @@ flatten_set_variable_args(const char *name, List *args)
 				else
 				{
 					/*
-					 * Plain string literal or identifier.  For quote mode,
+					 * Plain string literal or identifier.	For quote mode,
 					 * quote it if it's not a vanilla identifier.
 					 */
 					if (flags & GUC_LIST_QUOTE)
@@ -8034,7 +8108,7 @@ AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
 
 	/*
 	 * Only one backend is allowed to operate on PG_AUTOCONF_FILENAME at a
-	 * time.  Use AutoFileLock to ensure that.  We must hold the lock while
+	 * time.  Use AutoFileLock to ensure that.	We must hold the lock while
 	 * reading the old file contents.
 	 */
 	LWLockAcquire(AutoFileLock, LW_EXCLUSIVE);
@@ -8092,7 +8166,7 @@ AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
 						AutoConfTmpFileName)));
 
 	/*
-	 * Use a TRY block to clean up the file if we fail.  Since we need a TRY
+	 * Use a TRY block to clean up the file if we fail.	 Since we need a TRY
 	 * block anyway, OK to use BasicOpenFile rather than OpenTransientFile.
 	 */
 	PG_TRY();
@@ -8145,6 +8219,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
 				 errmsg("cannot set parameters during a parallel operation")));
+	MyProc->is_tainted = true;
 
 	switch (stmt->kind)
 	{
@@ -8175,7 +8250,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 				foreach(head, stmt->args)
 				{
-					DefElem    *item = (DefElem *) lfirst(head);
+					DefElem	   *item = (DefElem *) lfirst(head);
 
 					if (strcmp(item->defname, "transaction_isolation") == 0)
 						SetPGVariable("transaction_isolation",
@@ -8197,7 +8272,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 				foreach(head, stmt->args)
 				{
-					DefElem    *item = (DefElem *) lfirst(head);
+					DefElem	   *item = (DefElem *) lfirst(head);
 
 					if (strcmp(item->defname, "transaction_isolation") == 0)
 						SetPGVariable("default_transaction_isolation",
@@ -8215,7 +8290,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 			}
 			else if (strcmp(stmt->name, "TRANSACTION SNAPSHOT") == 0)
 			{
-				A_Const    *con = linitial_node(A_Const, stmt->args);
+				A_Const	   *con = linitial_node(A_Const, stmt->args);
 
 				if (stmt->is_local)
 					ereport(ERROR,
@@ -8369,7 +8444,7 @@ init_custom_variable(const char *name,
 	/*
 	 * We can't support custom GUC_LIST_QUOTE variables, because the wrong
 	 * things would happen if such a variable were set or pg_dump'd when the
-	 * defining extension isn't loaded.  Again, treat this as fatal because
+	 * defining extension isn't loaded.	 Again, treat this as fatal because
 	 * the loadable module may be partly initialized already.
 	 */
 	if (flags & GUC_LIST_QUOTE)
@@ -8378,7 +8453,7 @@ init_custom_variable(const char *name,
 	/*
 	 * Before pljava commit 398f3b876ed402bdaec8bc804f29e2be95c75139
 	 * (2015-12-15), two of that module's PGC_USERSET variables facilitated
-	 * trivial escalation to superuser privileges.  Restrict the variables to
+	 * trivial escalation to superuser privileges.	Restrict the variables to
 	 * protect sites that have yet to upgrade pljava.
 	 */
 	if (context == PGC_USERSET &&
@@ -8460,9 +8535,9 @@ define_custom_variable(struct config_generic *variable)
 	 * variable.  Essentially, we need to duplicate all the active and stacked
 	 * values, but with appropriate validation and datatype adjustment.
 	 *
-	 * If an assignment fails, we report a WARNING and keep going.  We don't
+	 * If an assignment fails, we report a WARNING and keep going.	We don't
 	 * want to throw ERROR for bad values, because it'd bollix the add-on
-	 * module that's presumably halfway through getting loaded.  In such cases
+	 * module that's presumably halfway through getting loaded.	 In such cases
 	 * the default or previous state will become active instead.
 	 */
 
@@ -8488,7 +8563,7 @@ define_custom_variable(struct config_generic *variable)
 	/*
 	 * Free up as much as we conveniently can of the placeholder structure.
 	 * (This neglects any stack items, so it's possible for some memory to be
-	 * leaked.  Since this can only happen once per session per variable, it
+	 * leaked.	Since this can only happen once per session per variable, it
 	 * doesn't seem worth spending much code on.)
 	 */
 	set_string_field(pHolder, pHolder->variable, NULL);
@@ -8566,9 +8641,9 @@ reapply_stacked_values(struct config_generic *variable,
 	else
 	{
 		/*
-		 * We are at the end of the stack.  If the active/previous value is
+		 * We are at the end of the stack.	If the active/previous value is
 		 * different from the reset value, it must represent a previously
-		 * committed session value.  Apply it, and then drop the stack entry
+		 * committed session value.	 Apply it, and then drop the stack entry
 		 * that set_config_option will have created under the impression that
 		 * this is to be just a transactional assignment.  (We leak the stack
 		 * entry.)
@@ -9279,7 +9354,7 @@ show_config_by_name(PG_FUNCTION_ARGS)
 
 /*
  * show_config_by_name_missing_ok - equiv to SHOW X command but implemented as
- * a function.  If X does not exist, suppress the error and just return NULL
+ * a function.	If X does not exist, suppress the error and just return NULL
  * if missing_ok is true.
  */
 Datum
@@ -9433,7 +9508,7 @@ show_all_settings(PG_FUNCTION_ARGS)
  * which includes the config file pathname, the line number, a sequence number
  * indicating the order in which the settings were encountered, the parameter
  * name and value, a bool showing if the value could be applied, and possibly
- * an associated error message.  (For problems such as syntax errors, the
+ * an associated error message.	 (For problems such as syntax errors, the
  * parameter name/value might be NULL.)
  *
  * Note: no filtering is done here, instead we depend on the GRANT system
@@ -9661,7 +9736,7 @@ _ShowOption(struct config_generic *record, bool use_units)
 
 /*
  *	These routines dump out all non-default GUC options into a binary
- *	file that is read by all exec'ed backends.  The format is:
+ *	file that is read by all exec'ed backends.	The format is:
  *
  *		variable name, string, null terminated
  *		variable value, string, null terminated
@@ -9896,14 +9971,14 @@ read_nondefault_variables(void)
  *
  * A PGC_S_DEFAULT setting on the serialize side will typically match new
  * postmaster children, but that can be false when got_SIGHUP == true and the
- * pending configuration change modifies this setting.  Nonetheless, we omit
+ * pending configuration change modifies this setting.	Nonetheless, we omit
  * PGC_S_DEFAULT settings from serialization and make up for that by restoring
  * defaults before applying serialized values.
  *
  * PGC_POSTMASTER variables always have the same value in every child of a
  * particular postmaster.  Most PGC_INTERNAL variables are compile-time
  * constants; a few, like server_encoding and lc_ctype, are handled specially
- * outside the serialize/restore procedure.  Therefore, SerializeGUCState()
+ * outside the serialize/restore procedure.	 Therefore, SerializeGUCState()
  * never sends these, and RestoreGUCState() never changes them.
  *
  * Role is a special variable in the sense that its current value can be an
@@ -9952,7 +10027,7 @@ estimate_variable_size(struct config_generic *gconf)
 
 				/*
 				 * Instead of getting the exact display length, use max
-				 * length.  Also reduce the max length for typical ranges of
+				 * length.	Also reduce the max length for typical ranges of
 				 * small values.  Maximum value is 2147483647, i.e. 10 chars.
 				 * Include one byte for sign.
 				 */
@@ -9968,7 +10043,7 @@ estimate_variable_size(struct config_generic *gconf)
 				/*
 				 * We are going to print it with %e with REALTYPE_PRECISION
 				 * fractional digits.  Account for sign, leading digit,
-				 * decimal point, and exponent with up to 3 digits.  E.g.
+				 * decimal point, and exponent with up to 3 digits.	 E.g.
 				 * -3.99329042340000021e+110
 				 */
 				valsize = 1 + 1 + 1 + REALTYPE_PRECISION + 5;
@@ -10324,7 +10399,7 @@ ParseLongOption(const char *string, char **name, char **value)
 
 /*
  * Handle options fetched from pg_db_role_setting.setconfig,
- * pg_proc.proconfig, etc.  Caller must specify proper context/source/action.
+ * pg_proc.proconfig, etc.	Caller must specify proper context/source/action.
  *
  * The array parameter must be an array of TEXT (it must not be NULL).
  */
@@ -10383,7 +10458,7 @@ ProcessGUCArray(ArrayType *array,

 /*
- * Add an entry to an option array.  The array parameter may be NULL
+ * Add an entry to an option array.	 The array parameter may be NULL
  * to indicate the current table entry is NULL.
  */
 ArrayType *
@@ -10463,7 +10538,7 @@ GUCArrayAdd(ArrayType *array, const char *name, const char *value)
 
 /*
  * Delete an entry from an option array.  The array parameter may be NULL
- * to indicate the current table entry is NULL.  Also, if the return value
+ * to indicate the current table entry is NULL.	 Also, if the return value
  * is NULL then a null should be stored.
  */
 ArrayType *
@@ -10604,8 +10679,8 @@ GUCArrayReset(ArrayType *array)
 /*
  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
  *
- * name is the option name.  value is the proposed value for the Add case,
- * or NULL for the Delete/Reset cases.  If skipIfNoPermissions is true, it's
+ * name is the option name.	 value is the proposed value for the Add case,
+ * or NULL for the Delete/Reset cases.	If skipIfNoPermissions is true, it's
  * not an error to have no permissions to set the option.
  *
  * Returns true if OK, false if skipIfNoPermissions is true and user does not
@@ -10627,13 +10702,13 @@ validate_option_array_item(const char *name, const char *value,
 	 * SUSET and user is superuser).
 	 *
 	 * name is not known, but exists or can be created as a placeholder (i.e.,
-	 * it has a prefixed name).  We allow this case if you're a superuser,
+	 * it has a prefixed name).	 We allow this case if you're a superuser,
 	 * otherwise not.  Superusers are assumed to know what they're doing. We
 	 * can't allow it for other users, because when the placeholder is
 	 * resolved it might turn out to be a SUSET variable;
 	 * define_custom_variable assumes we checked that.
 	 *
-	 * name is not known and can't be created as a placeholder.  Throw error,
+	 * name is not known and can't be created as a placeholder.	 Throw error,
 	 * unless skipIfNoPermissions is true, in which case return false.
 	 */
 	gconf = find_option(name, true, WARNING);
@@ -10686,7 +10761,7 @@ validate_option_array_item(const char *name, const char *value,
  * ERRCODE_INVALID_PARAMETER_VALUE SQLSTATE for check hook failures.
  *
  * Note that GUC_check_errmsg() etc are just macros that result in a direct
- * assignment to the associated variables.  That is ugly, but forced by the
+ * assignment to the associated variables.	That is ugly, but forced by the
  * limitations of C's macro mechanisms.
  */
 void
@@ -11122,7 +11197,7 @@ check_canonical_path(char **newval, void **extra, GucSource source)
 {
 	/*
 	 * Since canonicalize_path never enlarges the string, we can just modify
-	 * newval in-place.  But watch out for NULL, which is the default value
+	 * newval in-place.	 But watch out for NULL, which is the default value
 	 * for external_pid_file.
 	 */
 	if (*newval)
@@ -11135,7 +11210,7 @@ check_timezone_abbreviations(char **newval, void **extra, GucSource source)
 {
 	/*
 	 * The boot_val given above for timezone_abbreviations is NULL. When we
-	 * see this we just do nothing.  If this value isn't overridden from the
+	 * see this we just do nothing.	 If this value isn't overridden from the
 	 * config file then pg_timezone_abbrev_initialize() will eventually
 	 * replace it with "Default".  This hack has two purposes: to avoid
 	 * wasting cycles loading values that might soon be overridden from the
@@ -11173,7 +11248,7 @@ assign_timezone_abbreviations(const char *newval, void *extra)
 /*
  * pg_timezone_abbrev_initialize --- set default value if not done already
  *
- * This is called after initial loading of postgresql.conf.  If no
+ * This is called after initial loading of postgresql.conf.	 If no
  * timezone_abbreviations setting was found therein, select default.
  * If a non-default value is already installed, nothing will happen.
  *
@@ -11203,7 +11278,7 @@ assign_tcp_keepalives_idle(int newval, void *extra)
 	 * The kernel API provides no way to test a value without setting it; and
 	 * once we set it we might fail to unset it.  So there seems little point
 	 * in fully implementing the check-then-assign GUC API for these
-	 * variables.  Instead we just do the assignment on demand.  pqcomm.c
+	 * variables.  Instead we just do the assignment on demand.	 pqcomm.c
 	 * reports any problems via elog(LOG).
 	 *
 	 * This approach means that the GUC value might have little to do with the
@@ -11491,11 +11566,11 @@ assign_recovery_target_timeline(const char *newval, void *extra)
 
 /*
  * Recovery target settings: Only one of the several recovery_target* settings
- * may be set.  Setting a second one results in an error.  The global variable
- * recoveryTarget tracks which kind of recovery target was chosen.  Other
+ * may be set.	Setting a second one results in an error.  The global variable
+ * recoveryTarget tracks which kind of recovery target was chosen.	Other
  * variables store the actual target value (for example a string or a xid).
  * The assign functions of the parameters check whether a competing parameter
- * was already set.  But we want to allow setting the same parameter multiple
+ * was already set.	 But we want to allow setting the same parameter multiple
  * times.  We also want to allow unsetting a parameter and setting a different
  * one, so we unset recoveryTarget when the parameter is set to an empty
  * string.
diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index b07be12..dac74a2 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -506,7 +506,7 @@ MemoryContextStatsDetail(MemoryContext context, int max_children)
  * *totals (if given).
  */
 static void
-MemoryContextStatsInternal(MemoryContext context, int level,
+ MemoryContextStatsInternal(MemoryContext context, int level,
 						   bool print, int max_children,
 						   MemoryContextCounters *totals)
 {
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 8733524..5f528c1 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -10677,4 +10677,11 @@
   proname => 'pg_partition_root', prorettype => 'regclass',
   proargtypes => 'regclass', prosrc => 'pg_partition_root' },
 
+# builin connection pool
+{ oid => '3435', descr => 'information about connection pooler proxies workload',
+  proname => 'pg_pooler_state', prorows => '1000', proretset => 't',
+  provolatile => 'v', prorettype => 'record', proargtypes => '',
+  proallargtypes => '{int4,int4,int4,int4,int4,int4,int8,int8,int8}', proargmodes => '{o,o,o,o,o,o,o,o,o}',
+  proargnames => '{pid,n_clients,n_ssl_clients,n_pools,n_backends,n_dedicated_backends,tx_bytes,rx_bytes,n_transactions}', prosrc => 'pg_pooler_state' },
+
 ]
diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h
index 96415a9..6d1a926 100644
--- a/src/include/libpq/libpq-be.h
+++ b/src/include/libpq/libpq-be.h
@@ -51,7 +51,7 @@
 #include <security.h>
 #undef SECURITY_WIN32
 
-#ifndef ENABLE_GSS
+#if !defined(ENABLE_GSS) && !defined(GSS_BUFFER_STUB_DEFINED)
 /*
  * Define a fake structure compatible with GSSAPI on Unix.
  */
@@ -60,6 +60,7 @@ typedef struct
 	void	   *value;
 	int			length;
 } gss_buffer_desc;
+#define GSS_BUFFER_STUB_DEFINED
 #endif
 #endif							/* ENABLE_SSPI */
 
index 08a2576..1e12ee1 100644
index 61a24c2..86c0ef8 100644
 
index b5c03d9..3ea24a3 100644

index f4841fb..fbc31d6 100644
 
@@ -455,6 +456,7 @@ int			pgwin32_select(int nfds, fd_set *readfs, fd_set *writefds, fd_set *exceptf

 

index bd7af11..36312d4 100644

 typedef struct WaitEvent
@@ -149,6 +151,8 @@ typedef struct WaitEvent
 #endif
 } WaitEvent;
 
+extern bool WaitEventUseEpoll;
+
 /* forward declaration to avoid exposing latch.c implementation details */
 typedef struct WaitEventSet WaitEventSet;
 
@@ -177,6 +181,8 @@ extern int	WaitLatch(Latch *latch, int wakeEvents, long timeout,
 extern int	WaitLatchOrSocket(Latch *latch, int wakeEvents,
 							  pgsocket sock, long timeout, uint32 wait_event_info);
 
index ac7ee72..e7207e2 100644
 
 /* NOTE: "typedef struct PGPROC PGPROC" appears in storage/lock.h. */
diff --git a/src/include/utils/guc_tables.h b/src/include/utils/guc_tables.h
index d68976f..9ff45b1 100644
--- a/src/include/utils/guc_tables.h
+++ b/src/include/utils/guc_tables.h
@@ -58,6 +58,7 @@ enum config_group
 	CONN_AUTH_SETTINGS,
 	CONN_AUTH_AUTH,
 	CONN_AUTH_SSL,
+	CONN_POOLING,
 	RESOURCES,
 	RESOURCES_MEM,
 	RESOURCES_DISK,
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index c0b8e3f..24569d8 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -59,7 +59,7 @@
 #include <security.h>
 #undef SECURITY_WIN32
 
-#ifndef ENABLE_GSS
+#if !defined(ENABLE_GSS) && !defined(GSS_BUFFER_STUB_DEFINED)
 /*
  * Define a fake structure compatible with GSSAPI on Unix.
  */
@@ -68,6 +68,7 @@ typedef struct
 	void	   *value;
 	int			length;
 } gss_buffer_desc;
+#define GSS_BUFFER_STUB_DEFINED
 #endif
 #endif							/* ENABLE_SSPI */
 
index f274d80..fdf53e9 100644
index 3dea11e..39bd2de 100644
index a24cfd4..38dda4d 100644

 check-tests: all tablespace-setup | temp-install
 	$(pg_regress_check) $(REGRESS_OPTS) $(MAXCONNOPT) $(TESTS) $(EXTRA_TESTS)
diff --git a/src/test/regress/conn_proxy.conf b/src/test/regress/conn_proxy.conf
new file mode 100644
index 0000000..ebaa257
--- /dev/null
+++ b/src/test/regress/conn_proxy.conf
@@ -0,0 +1,3 @@
+connection_proxies = 1
+port = 5432
+log_statement=all
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index 973691c..bcbfec3 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -158,6 +158,7 @@ sub mkvcbuild
 
 	$postgres = $solution->AddProject('postgres', 'exe', '', 'src/backend');
 	$postgres->AddIncludeDir('src/backend');
+	$postgres->AddIncludeDir('src/port');
 	$postgres->AddDir('src/backend/port/win32');
 	$postgres->AddFile('src/backend/utils/fmgrtab.c');
 	$postgres->ReplaceFile('src/backend/port/pg_sema.c',
@@ -271,6 +272,12 @@ sub mkvcbuild
 	$libpqwalreceiver->AddIncludeDir('src/interfaces/libpq');
 	$libpqwalreceiver->AddReference($postgres, $libpq);
 
+	my $libpqconn =
+	  $solution->AddProject('libpqconn', 'dll', '',
+		'src/backend/postmaster/libpqconn');
+	$libpqconn->AddIncludeDir('src/interfaces/libpq');
+	$libpqconn->AddReference($postgres, $libpq);
+
 	my $pgoutput = $solution->AddProject('pgoutput', 'dll', '',
 		'src/backend/replication/pgoutput');
 	$pgoutput->AddReference($postgres);
diff --git a/src/tools/msvc/clean.bat b/src/tools/msvc/clean.bat
index d034ec5..ef6eb81 100755
--- a/src/tools/msvc/clean.bat
+++ b/src/tools/msvc/clean.bat
@@ -19,6 +19,7 @@ if exist pgsql.suo del /q /a:H pgsql.suo
 del /s /q src\bin\win32ver.rc 2> NUL
 del /s /q src\interfaces\win32ver.rc 2> NUL
 if exist src\backend\win32ver.rc del /q src\backend\win32ver.rc
+if exist src\backend\postmaster\libpqconn\win32ver.rc del /q src\backend\postmaster\libpqconn\win32ver.rc
 if exist src\backend\replication\libpqwalreceiver\win32ver.rc del /q src\backend\replication\libpqwalreceiver\win32ver.rc
 if exist src\backend\replication\pgoutput\win32ver.rc del /q src\backend\replication\pgoutput\win32ver.rc
 if exist src\backend\snowball\win32ver.rc del /q src\backend\snowball\win32ver.rc

---

From: Ryan Lambert <[email-masked]>
Date: Fri, 26 Jul 2019 10:20:34 -0600

> I attached new version of the patch with fixed indentation problems and

Great, this latest patch applies cleanly to master.  installcheck world
still passes.

> Using more than 1 proxy is be needed only for huge workloads (hundreds

My testing showed using only one proxy performing very poorly vs not using
the pooler, even at 300 connections, with -3% TPS.  At lower numbers of
connections it was much worse than other configurations I tried.  I just
shared my full pgbench results [1], the "No Pool" and "# Proxies 2" data is
what I used to generate the charts I previously shared.  The 1 proxy and 10
proxy data I had referred to but hadn't shared the results, sorry about
that.

>  worker can be large than number of cores.

I will do more testing around this variable next.  It seems that increasing
session_pool_size for connection_proxies = 1 might help and leaving it at
its default was my problem.

> parameter which allows to terminate idle workers.

+1

>  primary intention of this patch was to minimize changes in Postgres core

Understood.

I attached a patch to apply after your latest patch [2] with my suggested
changes to the docs.  I tried to make things read smoother without altering
your meaning.  I don't think the connection pooler chapter fits in The SQL
Language section, it seems more like Server Admin functionality so I moved
it to follow the chapter on HA, load balancing and replication.  That made
more sense to me looking at the overall ToC of the docs.

Thanks,

[1]
https://docs.google.com/spreadsheets/d/11XFoR26eiPQETUIlLGY5idG3fzJKEhuAjuKp6RVECOU
[2]
https://www.postgresql.org/message-id/attachment/102848/builtin_connection_proxy-11.patch

*Ryan*

---

From: Konstantin Knizhnik <[email-masked]>
Date: Fri, 26 Jul 2019 19:27:43 +0300

> I attached a patch to apply after your latest patch [2] with my 
> suggested changes to the docs.  I tried to make things read smoother 
> without altering your meaning.  I don't think the connection pooler 
> chapter fits in The SQL Language section, it seems more like Server 
> Admin functionality so I moved it to follow the chapter on HA, load 
> balancing and replication.  That made more sense to me looking at the 
> overall ToC of the docs.
>
Thank you.
I have committed your documentation changes in my Git repository and 
attach new patch with your corrections.

index 84341a3..2758506 100644
 
+          one connection proxy when session pooling is enabled.
index 0000000..a4b2720
@@ -0,0 +1,173 @@
+    For large number of clients this model can consume a large number of system
+    resources and lead to significant performance degradation, especially on computers with large
+    number of CPU cores. The reason is high contention between backends for Postgres resources.
+    Also, the size of many Postgres internal data structures are proportional to the number of
+    active backends as well as complexity of algorithms for the data structures.
+    This is why many production Postgres installation are using some kind of connection pooling, such as 
+    pgbouncer, J2EE, and odyssey.  Using an external connection pooler requires additional efforts for installation,
+    single-threaded and so can a be bottleneck on high load systems, so multiple instances of pgbouncer have to be launched.
+    Starting with version 12 <productname>PostgreSQL</productname> provides built-in connection pooler.
+    Built-in connection pooler accepts connections on a separate port (<varname>proxy_port</varname> configuration option, default value is 6543).
+    If client is connected to Postgres through standard port (<varname>port</varname> configuration option, default value is 5432), then normal (<emphasis>dedicated</emphasis>) backend is created. It works only
+    Right now sessions are bounded to proxy and can not migrate between them.
+    To provide uniform load balancing of proxies, postmaster uses one of three scheduling policies:
+    <varname>connection_proxies</varname> specifies the number of connection proxy processes to be spawned.
+    <varname>session_pool_size</varname> specifies the maximal number of backends per connection pool. Maximal number of launched non-dedicated backends in pooling mode is limited by
+    If the number of backends is too small, the server will not be able to utilize all system resources.
+    It is still necessary to have a port for direct connections to the database (dedicated backends).
+    Because pooled backends are not terminated on client exit, it will not
+    be possible to drop database to which they are connected.  It can be achieved without server restart using <varname>restart_pooler_on_reload</varname> variable. Setting this variable to <literal>true</literal> cause shutdown of all pooled backends after execution of <function>pg_reload_conf()</function> function. Then it will be possible to drop database.
+    Unlike pgbouncer and other external connection poolers, the built-in connection pooler doesn't require installation and configuration of some other components.
+    It also does not introduce any limitations for clients: existing clients can work through proxy and don't notice any difference.
+    Redirecting connections through the connection proxy definitely has a negative effect on total system performance, especially latency.
+    The overhead of the connection proxy depends on many factors, such as characteristics of external and internal networks, complexity of queries and size of returned result set.
+    With a small number of connections (10), pgbench benchmark in select-only mode shows almost two times worse performance for local connections through connection pooler compared with direct local connections. For much larger number of connections (when pooling is actually required), pooling mode outperforms direct connection mode.
+    state for long enough time. An <emphasis>idle-in-transaction</emphasis> backend can not be rescheduled for another session.
 
index 3e115f1..ee6e2bd 100644
@@ -158,6 +158,7 @@
   &maintenance;
   &backup;
   &high-availability;
   &monitoring;
   &diskusage;
   &wal;

 
 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

 
 
 	/*

 	/*

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

 	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 

 
 
 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
 
 	switch (stmt->kind)
 	{

 

 				if (stmt->is_local)
 					ereport(ERROR,

 /*
 
 /*
 
 				/*
 
 /*

 /*
 
 /*
 
 /*

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Tomas Vondra <[email-masked]>
Date: Fri, 26 Jul 2019 22:24:37 +0200

Hi Konstantin,

I've started reviewing this patch and experimenting with it, so let me
share some initial thoughts.

1) not handling session state (yet)

I understand handling session state would mean additional complexity, so
I'm OK with not having it in v1. That being said, I think this is the
primary issue with connection pooling on PostgreSQL - configuring and
running a separate pool is not free, of course, but when people complain
to us it's when they can't actually use a connection pool because of
this limitation.

So what are your plans regarding this feature? I think you mentioned
you already have the code in another product. Do you plan to submit it
in the pg13 cycle, or what's the plan? I'm willing to put some effort
into reviewing and testing that.

FWIW it'd be nice to expose it as some sort of interface, so that other
connection pools can leverage it too. There are use cases that don't
work with a built-in connection pool (say, PAUSE/RESUME in pgbouncer
allows restarting the database) so projects like pgbouncer or odyssey
are unlikely to disappear anytime soon.

I also wonder if we could make it more permissive even in v1, without
implementing dump/restore of session state.

Consider for example patterns like this:

  BEGIN;
  SET LOCAL enable_nestloop = off;
  ...
  COMMIT;

or

  PREPARE x(int) AS SELECT ...;
  EXECUTE x(1);
  EXECUTE x(2);
  ...
  EXECUTE x(100000);
  DEALLOCATE x;

or perhaps even

  CREATE FUNCTION f() AS $$ ... $$
  LANGUAGE sql
  SET enable_nestloop = off;

In all those cases (and I'm sure there are other similar examples) the
connection pool considers the session 'tainted' it marks it as tainted
and we never reset that. So even when an application tries to play nice,
it can't use pooling.

Would it be possible to maybe track this with more detail (number of
prepared statements, ignore SET LOCAL, ...)? That should allow us to do
pooling even without full support for restoring session state.

2) configuration

I think we need to rethink how the pool is configured. The options
available at the moment are more a consequence of the implementation and
are rather cumbersome to use in some cases.

For example, we have session_pool_size, which is (essentially) the
number of backends kept in the pool. Which seems fine at first, because
it seems like you might say

    max_connections = 100
    session_pool_size = 50

to say the connection pool will only ever use 50 connections, leaving
the rest for "direct" connection. But that does not work at all, because
the number of backends the pool can open is

    session_pool_size * connection_proxies * databases * roles

which pretty much means there's no limit, because while we can specify
the number of proxies, the number of databases and roles is arbitrary.
And there's no way to restrict which dbs/roles can use the pool.

So you can happily do this

    max_connections = 100
    connection_proxies = 4
    session_pool_size = 10

    pgbench -c 24 -U user1 test1
    pgbench -c 24 -U user2 test2
    pgbench -c 24 -U user3 test3
    pgbench -c 24 -U user4 test4

at which point it's pretty much game over, because each proxy has 4
pools, each with ~6 backends, 96 backends in total. And because
non-tainted connections are never closed, no other users/dbs can use the
pool (will just wait indefinitely).

To allow practical configurations, I think we need to be able to define:

* which users/dbs can use the connection pool
* minimum/maximum pool size per user, per db and per user/db
* maximum number of backend connections

We need to be able to close connections when needed (when not assigned,
and we need the connection for someone else).

Plus those limits need to be global, not "per proxy" - it's just strange
that increasing connection_proxies bumps up the effective pool size.

I don't know what's the best way to specify this configuration - whether
to store it in a separate file, in some system catalog, or what.

3) monitoring

I think we need much better monitoring capabilities. At this point we
have a single system catalog (well, a SRF) giving us proxy-level
summary. But I think we need much more detailed overview - probably
something like pgbouncer has - listing of client/backend sessions, with
various details.

Of course, that's difficult to do when those lists are stored in private
memory of each proxy process - I think we need to move this to shared
memory, which would also help to address some of the issues I mentioned
in the previous section (particularly that the limits need to be global,
not per proxy).

4) restart_pooler_on_reload

I find it quite strange that restart_pooler_on_reload binds restart of
the connection pool to reload of the configuration file. That seems like
a rather surprising behavior, and I don't see why would you ever want
that? Currently it seems like the only way to force the proxies to close
the connections (the docs mention DROP DATABASE), but why shouldn't we
have separate functions to do that? In particular, why would you want to
close connections for all databases and not just for the one you're
trying to drop?

5) session_schedule

It's nice we support different strategies to assign connections to
worker processes, but how do you tune it? How do you pick the right
option for your workload? We either need to provide metrics to allow
informed decision, or just not provide the option.

And "load average" may be a bit misleading term (as used in the section
about load-balancing option). It kinda suggests we're measuring how busy
the different proxies were recently (that's what load average in Unix
does) - by counting active processes, CPU usage or whatever.  But AFAICS
that's not what's happening at all - it just counts the connections,
with SSL connections counted as more expensive.

6) issues during testin

While testing, I've seen a couple of issues. Firstly, after specifying a
db that does not exist:

  psql -h localhost -p 6543 xyz

just hangs and waits forever. In the server log I see this:

  2019-07-25 23:16:50.229 CEST [31296] FATAL:  database "xyz" does not exist
  2019-07-25 23:16:50.258 CEST [31251] WARNING:  could not setup local connect to server
  2019-07-25 23:16:50.258 CEST [31251] DETAIL:  FATAL:  database "xyz" does not exist

But the client somehow does not get the message and waits.

Secondly, when trying this 

  pgbench -p 5432 -U x -i -s 1 test
  pgbench -p 6543 -U x -c 24 -C -T 10 test

it very quickly locks up, with plenty of non-granted locks in pg_locks,
but I don't see any interventions by deadlock detector so I presume
the issue is somewhere else. I don't see any such issues whe running
without the connection pool or without the -C option:

  pgbench -p 5432 -U x -c 24 -C -T 10 test
  pgbench -p 6543 -U x -c 24 -T 10 test

This is with default postgresql.conf, except for

  connection_proxies = 4

regards

-- 
Tomas Vondra                  http://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

---

From: Dave Cramer <[email-masked]>
Date: Sat, 27 Jul 2019 06:40:00 -0400

Responses inline. I just picked up this thread so please bear with me.

> into reviewing and testing that.

I too would like to see the plan of how to make this feature complete.

My concern here is that for the pgjdbc client at least *every* connection
does some set parameter so I see from what I can tell from scanning this
thread pooling would not be used at all.I suspect the .net driver does the
same thing.

> are unlikely to disappear anytime soon.

Agreed, and as for other projects. I see their value in having the pool on
a separate host as being a strength.  I certainly don't see them going
anywhere soon. Either way having a unified pooling API would be a useful
goal.

>   PREPARE x(int) AS SELECT ...;

Again pgjdbc does use server prepared statements so I'm assuming this would
not work for clients using pgjdbc or .net

Additionally we have setSchema, which is really set search_path, again
incompatible.

Regards,

Dave

---

From: Thomas Munro <[email-masked]>
Date: Sat, 27 Jul 2019 23:49:10 +1200

> I will be pleased if you can check it at FreeBSD  box.

I tried your v12 patch and it gets stuck in a busy loop during make
check.  You can see it on Linux with ./configure ...
CFLAGS="-DWAIT_USE_POLL".

--
Thomas Munro
https://enterprisedb.com

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 29 Jul 2019 19:14:27 +0300

> into reviewing and testing that.

I completely agree with you. My original motivation of implementation of 
built-in connection pooler
was to be able to preserve session semantic (prepared statements, GUCs, 
temporary tables) for pooled connections.
Almost all production system have to use some kind of pooling. But in 
case of using pgbouncer&Co we are loosing possibility
to use prepared statements which can cause up to two time performance 
penalty (in simple OLTP queries).
So I have implemented such version of connection pooler of PgPro EE.
It require many changes in Postgres core so I realized that there are no 
chances to commit in community
(taken in account that may other my patches like autoprepare and libpq 
compression are postponed for very long time, although
them are much smaller and less invasive).

Then Dimitri Fontaine proposed me to implement much simple version of 
pooler based on traditional proxy approach.
This patch is result of our conversation with Dimitri.
You are asking me about my plans... I think that it will be better to 
try first to polish this version of the patch and commit it and only 
after it add more sophisticated features
like saving/restoring session state.

> are unlikely to disappear anytime soon.

Obviously built-in connection pooler will never completely substitute 
external poolers like pgbouncer, which provide more flexibility, i.e. 
make it possible to install pooler at separate host or at client side.

> pooling even without full support for restoring session state.

Sorry, I do not completely understand your idea (how to implement this 
features without maintaining session state).
To implement prepared statements  we need to store them in session 
context or at least add some session specific prefix to prepare 
statement name.
Temporary tables also require per-session temporary table space. With 
GUCs situation is even more complicated - actually most of the time in 
my PgPro-EE pooler version
I have spent in the fight with GUCs (default values, reloading 
configuration, memory alllocation/deallocation,...).
But the "show stopper" are temporary tables: if them are accessed 
through internal (non-shared buffer), then you can not reschedule 
session to some other backend.
This is why I have now patch with implementation of global temporary 
tables (a-la Oracle) which has global metadata and are accessed though 
shared buffers (which also allows to use them
in parallel queries).

> to store it in a separate file, in some system catalog, or what.
Well, I agree with you, that maintaining separate connection pool for 
each database/role pain may be confusing.
My assumption was that in many configurations application are accessing 
the same (or few databases) with one (or very small) number of users.
If you have hundreds of databases or users (each connection to the 
database under its OS name), then
connection pooler will not work in any case, doesn't matter how you will 
configure it. It is true also for pgbouncer and any other pooler.
If Postgres backend is able to work only with on database, then you will 
have to start at least such number of backends as number of databases 
you have.
Situation with users is more obscure - it may be possible to implement 
multiuser access to the same backend (as it can be done now using "set 
role").

So I am not sure that if we implement sophisticated configurator which 
allows to specify in some configuration file for each database/role pair 
maximal/optimal number
of workers, then it completely eliminate the problem with multiple 
session pools.

Particularly, assume that we have 3 databases and want to server them 
with 10 workers.
Now we receive 10 requests to database A. We start 10 backends which 
server this queries.
The we receive 10 requests to database B. What should we do then. 
Terminate all this 10 backends and start new 10
instead of them? Or should we start 3 workers for database A, 3 workers 
for database B and 4 workers for database C.
In this case of most of requests are to database A, we will not be able 
to utilize all system resources.
Certainly we can specify in configuration file that database A needs 6 
workers and B/C - two workers.
But it will work only in case if we statically know workload...

So I have though a lot about it, but failed to find some good and 
flexible solution.
Looks like if you wan to efficiently do connection pooler, you should 
restrict number of
database and roles.

> in the previous section (particularly that the limits need to be global,
I also agree that more monitoring facilities are needed.
Just want to get better understanding what kind of information we need 
to monitor.
As far as pooler is done at transaction level, all non-active session 
are in idle state
and state of active sessions can be inspected using pg_stat_activity.

> close connections for all databases and not just for the one you're

Reload configuration is already broadcasted to all backends.
In case of using some other approach for controlling pool worker,
it will be necessary to implement own notification mechanism.
Certainly it is doable. But as I already wrote, the primary idea was to 
minimize
this patch and make it as less invasive as possible.

> informed decision, or just not provide the option.
The honest answer for this question is "I don't know".
I have just implemented few different policies and assume that people 
will test them on their workloads and
tell me which one will be most efficient. Then it will be possible to 
give some recommendations how to
choose policies.

Also current criteria for "load-balancing" may be too dubious.
May be formula should include some other metrics rather than just number 
of connected clients.

> with SSL connections counted as more expensive.
Generally I agree. Current criteria for "load-balancing" may be too dubious.
May be formula should include some other metrics rather than just number 
of connected clients.
But I failed to find such metrices. CPU usage? But proxy themselve are 
using CPU only for redirecting traffic.
Assume that one proxy is serving 10 clients performing OLAP queries and 
another one 100 clients performing OLTP queries.
Certainly OLTP queries are used to be executed much faster. But it is 
hard to estimate amount of transferred data for both proxies.
Generally OLTP queries are used to access few records, while OLAP access 
much more data. But OLAP queries usually performs some aggregation,
so final result may be also small...

Looks like we need to measure not only load of proxy itself but also 
load of proxies connected to this proxy.
But it requires much more efforts.

Fixed.

> This is with default postgresql.conf, except for
I need more time to investigate this problem.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 29 Jul 2019 19:19:08 +0300

> CFLAGS="-DWAIT_USE_POLL".

New version of the patch is attached which fixes poll() and Win32 
implementations of WaitEventSet.

 

 

+	if (FeBeWaitSet)
 
+

 

 
index 0000000..d950a8c
@@ -0,0 +1,49 @@
+libpq_connectdb(char const* keywords[], char const* values[], char** error)
+	if (conn && PQstatus(conn) != CONNECTION_OK)
+		*error = strdup(PQerrorMessage(conn));
+		PQfinish(conn);
+	*error = NULL;

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

index 0000000..ce8c3a3
@@ -0,0 +1,1103 @@
+#include "libpq/pqformat.h"
+static Channel* backend_start(SessionPool* pool, char** error);
+static void channel_hangout(Channel* chan, char const* op);
+static ssize_t socket_write(Channel* chan, char const* buf, size_t size);
+			char* error;
+			idle_backend = backend_start(chan->pool, &error);
+				if (error)
+					StringInfoData msgbuf;
+					initStringInfo(&msgbuf);
+					pq_sendbyte(&msgbuf, 'E');
+					pq_sendint32(&msgbuf, 7 + strlen(error));
+					pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
+					pq_sendstring(&msgbuf, error);
+					pq_sendbyte(&msgbuf, '\0');
+					socket_write(chan, msgbuf.data, msgbuf.len);
+					pfree(msgbuf.data);
+					free(error);
+				channel_hangout(chan, "connect");
+backend_start(SessionPool* pool, char** error)
+	conn = LibpqConnectdbParams(keywords, values, error);
+			char* error;
+			Channel* new_backend = backend_start(chan->pool, &error);
+				free(error);

 	/*
index 2426cbc..c7fc97d 100644
@@ -72,11 +72,29 @@
 
+#if defined(WAIT_USE_EPOLL)
+bool WaitEventUseEpoll = true;
+#else
+bool WaitEventUseEpoll = false;
+#endif
+
+/*
+ * Connection pooler needs to delete events from event set.
+ * As far as we have too preserve positions of all other events,
+ * we can not move events. So we have to maintain list of free events.
+ * But poll/WaitForMultipleObjects manipulates with array of listened events.
+ * That is why elements in pollfds and handle arrays should be stored without holes
+ * and we need to maintain mapping between them and WaitEventSet events.
+ * This mapping is stored in "permutation" array. Also we need backward mapping
+ * (from event to descriptors array) which is implemented using "index" field of WaitEvent.
+ */
+
 /* typedef in latch.h */
 struct WaitEventSet
 {
 	int			nevents;		/* number of registered events */
 	int			nevents_space;	/* maximum number of events in this set */
+	int         free_events;    /* L1-list of free events linked by "pos" and terminated by -1. */
 
 	/*
 	 * Array, of nevents_space length, storing the definition of events this
@@ -84,6 +102,8 @@ struct WaitEventSet
 	 */
 	WaitEvent  *events;
 
+	int        *permutation;    /* indexes of used events (see comment above) */
+
 	/*
 	 * If WL_LATCH_SET is specified in any wait event, latch is a pointer to
 	 * said latch, and latch_pos the offset in the ->events array. This is
@@ -137,9 +157,9 @@ static void drainSelfPipe(void);
 #if defined(WAIT_USE_EPOLL)
 static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action);
 #elif defined(WAIT_USE_POLL)
-static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event, bool remove);
 #elif defined(WAIT_USE_WIN32)
-static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event, bool remove);
 #endif
 
 static inline int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
@@ -553,6 +573,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 	 */
 	sz += MAXALIGN(sizeof(WaitEventSet));
 	sz += MAXALIGN(sizeof(WaitEvent) * nevents);
+	sz += MAXALIGN(sizeof(int) * nevents);
 
 #if defined(WAIT_USE_EPOLL)
 	sz += MAXALIGN(sizeof(struct epoll_event) * nevents);
@@ -571,6 +592,9 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 	set->events = (WaitEvent *) data;
 	data += MAXALIGN(sizeof(WaitEvent) * nevents);
 
+	set->permutation = (int *) data;
+	data += MAXALIGN(sizeof(int) * nevents);
+
 #if defined(WAIT_USE_EPOLL)
 	set->epoll_ret_events = (struct epoll_event *) data;
 	data += MAXALIGN(sizeof(struct epoll_event) * nevents);
@@ -585,6 +609,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 	set->latch = NULL;
 	set->nevents_space = nevents;
 	set->exit_on_postmaster_death = false;
+	set->free_events = -1;
 
 #if defined(WAIT_USE_EPOLL)
 #ifdef EPOLL_CLOEXEC
@@ -632,12 +657,11 @@ FreeWaitEventSet(WaitEventSet *set)
 #if defined(WAIT_USE_EPOLL)
 	close(set->epoll_fd);
 #elif defined(WAIT_USE_WIN32)
-	WaitEvent  *cur_event;
+	int i;
 
-	for (cur_event = set->events;
-		 cur_event < (set->events + set->nevents);
-		 cur_event++)
+	for (i = 0; i < set->nevents; i++)
 	{
+		WaitEvent* cur_event = &set->events[set->permutation[i]];
 		if (cur_event->events & WL_LATCH_SET)
 		{
 			/* uses the latch's HANDLE */
@@ -650,7 +674,7 @@ FreeWaitEventSet(WaitEventSet *set)
 		{
 			/* Clean up the event object we created for the socket */
 			WSAEventSelect(cur_event->fd, NULL, 0);
-			WSACloseEvent(set->handles[cur_event->pos + 1]);
+			WSACloseEvent(set->handles[cur_event->index + 1]);
 		}
 	}
 #endif
@@ -691,9 +715,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -720,8 +746,20 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
+	set->permutation[set->nevents] = event->pos;
+	event->index = set->nevents++;
@@ -748,15 +786,41 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
 /*
+ * Remove event with specified socket descriptor
+ */
+void DeleteWaitEventFromSet(WaitEventSet *set, int event_pos)
+{
+	WaitEvent  *event = &set->events[event_pos];
+#if defined(WAIT_USE_EPOLL)
+	WaitEventAdjustEpoll(set, event, EPOLL_CTL_DEL);
+#elif defined(WAIT_USE_POLL)
+	WaitEventAdjustPoll(set, event, true);
+#elif defined(WAIT_USE_WIN32)
+	WaitEventAdjustWin32(set, event, true);
+#endif
+	if (--set->nevents != 0)
+	{
+		set->permutation[event->index] = set->permutation[set->nevents];
+		set->events[set->permutation[set->nevents]].index = event->index;
+	}
+	event->fd = PGINVALID_SOCKET;
+	event->events = 0;
+	event->index = -1;
+	event->pos = set->free_events;
+	set->free_events = event_pos;
+}
+
+
+/*
  * Change the event mask and, in the WL_LATCH_SET case, the latch associated
  * with the WaitEvent.
  *
@@ -767,10 +831,16 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 {
 	WaitEvent  *event;

 
@@ -804,9 +874,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
@@ -844,6 +914,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -852,11 +924,10 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
 }
@@ -864,11 +935,16 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 #if defined(WAIT_USE_POLL)
 static void
-WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event, bool remove)
 {
-	struct pollfd *pollfd = &set->pollfds[event->pos];
+	struct pollfd *pollfd = &set->pollfds[event->index];
+
+	if (remove)
+	{
+		*pollfd = set->pollfds[set->nevents - 1]; /* nevents is not decremented yet */
+		return;
+	}
 
-	pollfd->revents = 0;
 	pollfd->fd = event->fd;
 
 	/* prepare pollfd entry once */
@@ -897,9 +973,20 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
 
 #if defined(WAIT_USE_WIN32)
 static void
-WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
+WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event, bool remove)
 {
-	HANDLE	   *handle = &set->handles[event->pos + 1];
+	HANDLE	   *handle = &set->handles[event->index + 1];
+
+	if (remove)
+	{
+		Assert(event->fd != PGINVALID_SOCKET);
+
+		if (*handle != WSA_INVALID_EVENT)
+			WSACloseEvent(*handle);
+
+		*handle = set->handles[set->nevents]; /* nevents is not decremented yet but we need to add 1 to the index */
+		return;
+	}
 
 	if (event->events == WL_LATCH_SET)
 	{
@@ -912,7 +999,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
@@ -929,8 +1016,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 
 		Assert(event->fd != PGINVALID_SOCKET);
 	}
@@ -1200,11 +1287,12 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 {
 	int			returned_events = 0;
 	int			rc;
-	WaitEvent  *cur_event;
-	struct pollfd *cur_pollfd;
+	int			i;
+	struct pollfd *cur_pollfd = set->pollfds;
+	WaitEvent* cur_event;
 
 	/* Sleep */
-	rc = poll(set->pollfds, set->nevents, (int) cur_timeout);
+	rc = poll(cur_pollfd, set->nevents, (int) cur_timeout);
 
 	/* Check return code */
 	if (rc < 0)
@@ -1227,15 +1315,13 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 		return -1;
 	}
 
-	for (cur_event = set->events, cur_pollfd = set->pollfds;
-		 cur_event < (set->events + set->nevents) &&
-		 returned_events < nevents;
-		 cur_event++, cur_pollfd++)
+	for (i = 0; i < set->nevents && returned_events < nevents; i++, cur_pollfd++)
 	{
 		/* no activity on this FD, skip */
 		if (cur_pollfd->revents == 0)
 			continue;
 
+		cur_event = &set->events[set->permutation[i]];
 		occurred_events->pos = cur_event->pos;
 		occurred_events->user_data = cur_event->user_data;
 		occurred_events->events = 0;
@@ -1326,17 +1412,24 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 					  WaitEvent *occurred_events, int nevents)
 {
 	int			returned_events = 0;
+	int			i;
 	DWORD		rc;
-	WaitEvent  *cur_event;
 
 	/* Reset any wait events that need it */
-	for (cur_event = set->events;
-		 cur_event < (set->events + set->nevents);
-		 cur_event++)
+	for (i = 0; i < set->nevents; i++)
 	{
-		if (cur_event->reset)
+		WaitEvent* cur_event = &set->events[set->permutation[i]];
+
+		/*
+		 * I have problem at Windows when SSPI connections "hanged" in WaitForMultipleObjects which
+		 * doesn't signal presence of input data (while it is possible to read this data from the socket).
+		 * Looks like "reset" logic is not completely correct (resetting event just after
+		 * receiveing presious read event). Reseting all read events fixes this problem.
+		 */
+		if (cur_event->events & WL_SOCKET_READABLE)
+		/* if (cur_event->reset) */
 		{
-			WaitEventAdjustWin32(set, cur_event);
+			WaitEventAdjustWin32(set, cur_event, false);
 			cur_event->reset = false;
 		}
 
@@ -1402,7 +1495,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 	 * With an offset of one, due to the always present pgwin32_signal_event,
 	 * the handle offset directly corresponds to a wait event.
 	 */
-	cur_event = (WaitEvent *) &set->events[rc - WAIT_OBJECT_0 - 1];
+	cur_event = (WaitEvent *) &set->events[set->permutation[rc - WAIT_OBJECT_0 - 1]];
 
 	occurred_events->pos = cur_event->pos;
 	occurred_events->user_data = cur_event->user_data;
@@ -1443,7 +1536,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 	else if (cur_event->events & WL_SOCKET_MASK)
 	{
 		WSANETWORKEVENTS resEvents;
-		HANDLE		handle = set->handles[cur_event->pos + 1];
+		HANDLE		handle = set->handles[cur_event->index + 1];
 
 		Assert(cur_event->fd);

 

 
 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
 
 	switch (stmt->kind)
 	{

 

 				if (stmt->is_local)
 					ereport(ERROR,

 /*
 
 /*
 
 				/*
 
 /*

 /*
 
 /*
 
 /*

-#ifndef ENABLE_GSS

 

 
 
index 8ccd2af..8e2079b 100644

+extern PGDLLIMPORT void* (*LibpqConnectdbParams)(char const* keywords[], char const* values[], char** errmsg);
+
+struct Proxy;
+struct Port;
+
 
index bd7af11..1dfac95 100644

 typedef struct WaitEvent
@@ -143,12 +145,15 @@ typedef struct WaitEvent
 	int			pos;			/* position in the event data structure */
 	uint32		events;			/* triggered events */
 	pgsocket	fd;				/* socket fd associated with event */
+	int         index;          /* position of correspondent element in descriptors array (for poll() and win32 implementation */
 	void	   *user_data;		/* pointer provided in AddWaitEventToSet */
 #ifdef WIN32
 	bool		reset;			/* Is reset of the event required? */
 #endif
 } WaitEvent;

@@ -177,6 +182,8 @@ extern int	WaitLatch(Latch *latch, int wakeEvents, long timeout,
 extern int	WaitLatchOrSocket(Latch *latch, int wakeEvents,
 							  pgsocket sock, long timeout, uint32 wait_event_info);

 
-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Tomas Vondra <[email-masked]>
Date: Tue, 30 Jul 2019 03:02:40 +0200

On Mon, Jul 29, 2019 at 07:14:27PM +0300, Konstantin Knizhnik wrote:
>I completely agree with you. My original motivation of implementation 
>of built-in connection pooler
>was to be able to preserve session semantic (prepared statements, 
>GUCs, temporary tables) for pooled connections.
>It require many changes in Postgres core so I realized that there are 
>no chances to commit in community

Well, I understand the history of this patch, and I have no problem with
getting a v1 of a connection pool without this feature. After all,
that's the idea of incremental development. But that only works when v1
allows adding that feature in v2, and I can't quite judge that. Which
is why I've asked you about your plans, because you clearly have more
insight thanks to writing the pooler for PgPro EE.

>make it possible to install pooler at separate host or at client side.

Sure. But that wasn't really my point - I was suggesting to expose this
hypothetical feature (managing session state) as some sort of API usable
from other connection pools.

>features without maintaining session state).

My idea (sorry if it wasn't too clear) was that we might handle some
cases more gracefully.

For example, if we only switch between transactions, we don't quite care
about 'SET LOCAL' (but the current patch does set the tainted flag). The
same thing applies to GUCs set for a function. 

For prepared statements, we might count the number of statements we
prepared and deallocated, and treat it as 'not tained' when there are no
statements. Maybe there's some risk I can't think of.

The same thing applies to temporary tables - if you create and drop a
temporary table, is there a reason to still treat the session as tained?

>shared buffers (which also allows to use them

Yeah, temporary tables are messy. Global temporary tables would be nice,
not just because of this, but also because of catalog bloat.

>each database/role pain may be confusing.

Anything can be confusing ...

>My assumption was that in many configurations application are 
>accessing the same (or few databases) with one (or very small) number 
>of users.
>connection pooler will not work in any case, doesn't matter how you 
>will configure it. It is true also for pgbouncer and any other pooler.

Sure, but I don't expect connection pool to work in such cases.

But I do expect to be able to configure which users can use the
connection pool at all, and maybe assign them different pool sizes.

>If Postgres backend is able to work only with on database, then you 
>will have to start at least such number of backends as number of 
>databases you have.

I don't think I've said we need anything like that. The way I'd expect
it to work that when we run out of backend connections, we terminate
some existing ones (and then fork new backends).

>allows to specify in some configuration file for each database/role 
>pair maximal/optimal number

Why would we need to invent any sophisticated configurator? Why couldn't
we use some version of what pgbouncer already does, or maybe integrate
it somehow into pg_hba.conf?

>instead of them? Or should we start 3 workers for database A, 3 
>workers for database B and 4 workers for database C.
>In this case of most of requests are to database A, we will not be 
>able to utilize all system resources.

My concern is not as much performance as inability to access the
database at all. There's no reasonable way to "guarantee" some number of
connections to a given database. Which is what pgbouncer does (through
min_pool_size).

Yes, it requires knowledge of the workload, and I don't think that's an
issue.

>Looks like if you wan to efficiently do connection pooler, you should 

I agree we should not over-complicate this, but I still find the current
configuration insufficient.

>and state of active sessions can be inspected using pg_stat_activity.

Except when sessions are tainted, for example. And when the transactions
are long-running, it's still useful to list the connections.

I'd suggest looking at the stats available in pgbouncer, most of that
actually comes from practice (monitoring metrics, etc.)

>Certainly it is doable. But as I already wrote, the primary idea was 
>to minimize

OK

>May be formula should include some other metrics rather than just 
>number of connected clients.
>

OK

>May be formula should include some other metrics rather than just 
>number of connected clients.
>Assume that one proxy is serving 10 clients performing OLAP queries 
>and another one 100 clients performing OLTP queries.
>Generally OLTP queries are used to access few records, while OLAP 
>access much more data. But OLAP queries usually performs some 
>aggregation,

I think "smart" load-balancing is fairly difficult to get right. I'd
just cut it from initial patch, keeping just the simple strategies
(random, round-robin).

>I need more time to investigate this problem.

OK

regards

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 30 Jul 2019 13:01:48 +0300

> temporary table, is there a reason to still treat the session as tained?

I already handling temporary tables with transaction scope (created 
using "create temp table ... on commit drop" command) - backend is not 
marked as tainted in this case.
Thank you for your notice about "set local" command - attached patch is 
also handling such GUCs.

>> GUCs situation is even more complicated - actually most of the time 
>> in my PgPro-EE pooler version
>> tables (a-la Oracle) which has global metadata and are accessed 
>> though shared buffers (which also allows to use them
>> in parallel queries).
>>
>

Global temp tables solves two problems:
1. catalog bloating
2. parallel query execution.

Them are not solving problem with using temporary tables at replica.
May be this problem can be solved by implementing special table access 
method for temporary tables.
But I am still no sure how useful will be such implementation of special 
table access method for temporary tables.
Obviously it requires much more efforts (need to reimplement a lot of 
heapam stuff).
But it will allow to eliminate MVCC overhead for temporary tuple and may 
be also reduce space by reducing size of tuple header.

>> Situation with users is more obscure - it may be possible to 
>> implement multiuser access to the same backend (as it can be done now 
>> using "set role").
>>
>

I afraid that it may eliminate most of positive effect of session 
pooling if we will  terminate and launch new backends without any 
attempt to bind backends to database and reuse them.

>
>> So I am not sure that if we implement sophisticated configurator 
>> which allows to specify in some configuration file for each 
>> database/role pair maximal/optimal number

I didn't think about such possibility.
But I suspect many problems with reusing pgbouncer code and moving it to 
Postgres core.

>> Just want to get better understanding what kind of information we 
>> need to monitor.
Tainted backends are very similar with normal postgres backends.
The only difference is that them are still connected with client though 
proxy.
What I wanted to say is that pg_stat_activity will show you information 
about all active transactions
even in case of connection polling.  You will no get information about 
pended sessions, waiting for
idle backends. But such session do not have any state (transaction is 
not started yet). So there is no much useful information
we can show about them except just number of such pended sessions.

 

 

+	if (FeBeWaitSet)
 
+

 

 
index 688ad43..049a76d 100644

 
 /*
  * Set by the -o option
 
+void* (*LibpqConnectdbParams)(char const* keywords[], char const* values[], char** error);
 
 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

 
 
 	/*
index 2426cbc..c36e9a2 100644

 	/*

 
@@ -571,20 +592,21 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 
+	set->permutation = (int *) data;
+	data += MAXALIGN(sizeof(int) * nevents);
+
 #if defined(WAIT_USE_EPOLL)
 	set->epoll_ret_events = (struct epoll_event *) data;
-	data += MAXALIGN(sizeof(struct epoll_event) * nevents);
 #elif defined(WAIT_USE_POLL)
 	set->pollfds = (struct pollfd *) data;
-	data += MAXALIGN(sizeof(struct pollfd) * nevents);
 #elif defined(WAIT_USE_WIN32)
-	set->handles = (HANDLE) data;
-	data += MAXALIGN(sizeof(HANDLE) * nevents);
+	set->handles = (HANDLE*) data;
 #endif
 
 	set->latch = NULL;
 
 #if defined(WAIT_USE_EPOLL)
 #ifdef EPOLL_CLOEXEC
@@ -632,12 +654,11 @@ FreeWaitEventSet(WaitEventSet *set)
 #if defined(WAIT_USE_EPOLL)
 	close(set->epoll_fd);
 #elif defined(WAIT_USE_WIN32)
-	WaitEvent  *cur_event;
+	int i;
 
@@ -650,7 +671,7 @@ FreeWaitEventSet(WaitEventSet *set)
@@ -691,9 +712,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -720,8 +743,20 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
@@ -748,15 +783,41 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
 /*
@@ -767,10 +828,16 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 {
 	WaitEvent  *event;

 
@@ -804,9 +871,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
@@ -844,6 +911,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -852,11 +921,10 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
 }
@@ -864,11 +932,16 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;
 
 	/* prepare pollfd entry once */
@@ -897,9 +970,21 @@ WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
 
+		set->handles[set->nevents] = WSA_INVALID_EVENT;
+		return;
+	}
 
 	if (event->events == WL_LATCH_SET)
 	{
@@ -912,7 +997,7 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 	}
 	else
 	{
-		int			flags = FD_CLOSE;	/* always check for errors/EOF */
+		int flags = FD_CLOSE;	/* always check for errors/EOF */
 
@@ -929,8 +1014,8 @@ WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event)
 
 		Assert(event->fd != PGINVALID_SOCKET);
 	}
@@ -1200,11 +1285,12 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 {
 	int			returned_events = 0;
 	int			rc;
-	WaitEvent  *cur_event;
-	struct pollfd *cur_pollfd;
+	int			i;
+	struct pollfd *cur_pollfd = set->pollfds;
+	WaitEvent* cur_event;
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)
@@ -1227,15 +1313,13 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 		return -1;
 	}

@@ -1326,17 +1410,25 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,

@@ -1402,7 +1494,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
@@ -1443,7 +1535,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
 		Assert(cur_event->fd);
 
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 498373f..3e530e7 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -397,6 +397,7 @@ InitProcess(void)
 	MyProc->roleId = InvalidOid;
 	MyProc->tempNamespaceId = InvalidOid;
 	MyProc->isBackgroundWorker = IsBackgroundWorker;
+	MyProc->is_tainted = false;
 	MyPgXact->delayChkpt = false;
 	MyPgXact->vacuumFlags = 0;
 	/* NB -- autovac launcher intentionally does not set IS_AUTOVACUUM */
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 44a59e1..62ec2af 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -4217,6 +4217,8 @@ PostgresMain(int argc, char *argv[],
 		 */
 		if (ConfigReloadPending)
 		{
+			if (RestartPoolerOnReload && strcmp(application_name, "pool_worker") == 0)
+				proc_exit(0);
 			ConfigReloadPending = false;
 			ProcessConfigFile(PGC_SIGHUP);
 		}
diff --git a/src/backend/utils/adt/lockfuncs.c b/src/backend/utils/adt/lockfuncs.c
index ffd1970..16ca58d 100644
--- a/src/backend/utils/adt/lockfuncs.c
+++ b/src/backend/utils/adt/lockfuncs.c
@@ -18,6 +18,7 @@
 #include "funcapi.h"
 #include "miscadmin.h"
 #include "storage/predicate_internals.h"
+#include "storage/proc.h"
 #include "utils/array.h"
 #include "utils/builtins.h"

 
index 92c4fee..60d4d8c 100644

 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
@@ -8146,6 +8220,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
+		MyProc->is_tainted = true;
+
 	switch (stmt->kind)
 	{
 		case VAR_SET_VALUE:
@@ -8175,7 +8252,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)

 					if (strcmp(item->defname, "transaction_isolation") == 0)
 						SetPGVariable("transaction_isolation",
@@ -8197,7 +8274,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)

@@ -8215,7 +8292,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 				if (stmt->is_local)
 					ereport(ERROR,
@@ -8369,7 +8446,7 @@ init_custom_variable(const char *name,
 	/*
@@ -8378,7 +8455,7 @@ init_custom_variable(const char *name,
@@ -8460,9 +8537,9 @@ define_custom_variable(struct config_generic *variable)
 
@@ -8488,7 +8565,7 @@ define_custom_variable(struct config_generic *variable)
 	/*
@@ -8566,9 +8643,9 @@ reapply_stacked_values(struct config_generic *variable,
@@ -9279,7 +9356,7 @@ show_config_by_name(PG_FUNCTION_ARGS)
 
 /*
@@ -9433,7 +9510,7 @@ show_all_settings(PG_FUNCTION_ARGS)
@@ -9661,7 +9738,7 @@ _ShowOption(struct config_generic *record, bool use_units)
 
 /*
@@ -9896,14 +9973,14 @@ read_nondefault_variables(void)
@@ -9952,7 +10029,7 @@ estimate_variable_size(struct config_generic *gconf)
 
 				/*
@@ -9968,7 +10045,7 @@ estimate_variable_size(struct config_generic *gconf)
@@ -10324,7 +10401,7 @@ ParseLongOption(const char *string, char **name, char **value)
 
 /*
@@ -10383,7 +10460,7 @@ ProcessGUCArray(ArrayType *array,

 /*
- * Add an entry to an option array.  The array parameter may be NULL
+ * Add an entry to an option array.	 The array parameter may be NULL
  * to indicate the current table entry is NULL.
  */
 ArrayType *
@@ -10463,7 +10540,7 @@ GUCArrayAdd(ArrayType *array, const char *name, const char *value)
 
 /*
@@ -10604,8 +10681,8 @@ GUCArrayReset(ArrayType *array)
@@ -10627,13 +10704,13 @@ validate_option_array_item(const char *name, const char *value,
@@ -10686,7 +10763,7 @@ validate_option_array_item(const char *name, const char *value,
@@ -11122,7 +11199,7 @@ check_canonical_path(char **newval, void **extra, GucSource source)
@@ -11135,7 +11212,7 @@ check_timezone_abbreviations(char **newval, void **extra, GucSource source)
@@ -11173,7 +11250,7 @@ assign_timezone_abbreviations(const char *newval, void *extra)
@@ -11203,7 +11280,7 @@ assign_tcp_keepalives_idle(int newval, void *extra)
@@ -11491,11 +11568,11 @@ assign_recovery_target_timeline(const char *newval, void *extra)
 
 /*

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 30 Jul 2019 14:06:38 +0300

> This is with default postgresql.conf, except for

After some investigation I tend to think that it is problem of pgbench.
It synchronously establishes new connection:

#0  0x00007f022edb7730 in __poll_nocancel () at 
../sysdeps/unix/syscall-template.S:84
#1  0x00007f022f7ceb77 in pqSocketPoll (sock=4, forRead=1, forWrite=0, 
end_time=-1) at fe-misc.c:1164
#2  0x00007f022f7cea32 in pqSocketCheck (conn=0x1273bf0, forRead=1, 
forWrite=0, end_time=-1) at fe-misc.c:1106
#3  0x00007f022f7ce8f2 in pqWaitTimed (forRead=1, forWrite=0, 
conn=0x1273bf0, finish_time=-1) at fe-misc.c:1038
#4  0x00007f022f7c0cdb in connectDBComplete (conn=0x1273bf0) at 
fe-connect.c:2029
#5  0x00007f022f7be71f in PQconnectdbParams (keywords=0x7ffc1add5640, 
values=0x7ffc1add5680, expand_dbname=1) at fe-connect.c:619
#6  0x0000000000403a4e in doConnect () at pgbench.c:1185
#7  0x0000000000407715 in advanceConnectionState (thread=0x1268570, 
st=0x1261778, agg=0x7ffc1add5880) at pgbench.c:2919
#8  0x000000000040f1b1 in threadRun (arg=0x1268570) at pgbench.c:6121
#9  0x000000000040e59d in main (argc=10, argv=0x7ffc1add5f98) at 
pgbench.c:5848

I.e. is starts normal transaction in one connection (few 
select/update/insert statement which are part of pgbench standard 
transaction)
and at the same time tries to establish new connection.
As far as built-in connection pooler performs transaction level 
scheduling, first session is grabbing backend until end of transaction. 
So until this transaction is
completed backend will not be able to process some other transaction or 
accept new connection. But pgbench is completing this transaction 
because it is blocked
in waiting response for new connection.

The problem can be easily reproduced with just two connections if 
connection_proxies=1 and session_pool_size=1:

  pgbench -p 6543 -n -c 2 -C -T 10 postgres
<hanged>

knizhnik@knizhnik:~/postgrespro.ee11$ ps aux | fgrep postgres
knizhnik 14425  0.0  0.1 172220 17540 ?        Ss   09:48   0:00 
/home/knizhnik/postgresql.builtin_pool/dist/bin/postgres -D pgsql.proxy
knizhnik 14427  0.0  0.0 183440  5052 ?        Ss   09:48   0:00 
postgres: connection proxy
knizhnik 14428  0.0  0.0 172328  4580 ?        Ss   09:48   0:00 
postgres: checkpointer
knizhnik 14429  0.0  0.0 172220  4892 ?        Ss   09:48   0:00 
postgres: background writer
knizhnik 14430  0.0  0.0 172220  7692 ?        Ss   09:48   0:00 
postgres: walwriter
knizhnik 14431  0.0  0.0 172760  5640 ?        Ss   09:48   0:00 
postgres: autovacuum launcher
knizhnik 14432  0.0  0.0  26772  2292 ?        Ss   09:48   0:00 
postgres: stats collector
knizhnik 14433  0.0  0.0 172764  5884 ?        Ss   09:48   0:00 
postgres: logical replication launcher
knizhnik 14434  0.0  0.0  22740  3084 pts/21   S+   09:48   0:00 pgbench 
-p 6543 -n -c 2 -C -T 10 postgres
knizhnik 14435  0.0  0.0 173828 13400 ?        Ss   09:48   0:00 
postgres: knizhnik postgres [local] idle in transaction
knizhnik 21927  0.0  0.0  11280   936 pts/19   S+   11:58   0:00 grep -F 
--color=auto postgres

But if you run each connection in separate thread, then this test is 
normally completed:

nizhnik@knizhnik:~/postgresql.builtin_pool$ pgbench -p 6543 -n -j 2 -c 2 
-C -T 10 postgres
transaction type: <builtin: TPC-B (sort of)>
scaling factor: 1
query mode: simple
number of clients: 2
number of threads: 2
duration: 10 s
number of transactions actually processed: 9036
latency average = 2.214 ms
tps = 903.466234 (including connections establishing)
tps = 1809.317395 (excluding connections establishing)

-- 

Konstantin Knizhnik

---

From: Tomas Vondra <[email-masked]>
Date: Tue, 30 Jul 2019 15:12:46 +0200

On Tue, Jul 30, 2019 at 01:01:48PM +0300, Konstantin Knizhnik wrote:
>Thank you for your notice about "set local" command - attached patch 
>is also handling such GUCs.
>

Thanks.

>>>Temporary tables also require per-session temporary table space. 
>>>With GUCs situation is even more complicated - actually most of 
>>>the time in my PgPro-EE pooler version
>>>This is why I have now patch with implementation of global 
>>>temporary tables (a-la Oracle) which has global metadata and are 
>>>accessed though shared buffers (which also allows to use them
>>>in parallel queries).
>>>
>>
>But I am still no sure how useful will be such implementation of 
>special table access method for temporary tables.
>But it will allow to eliminate MVCC overhead for temporary tuple and 
>may be also reduce space by reducing size of tuple header.
>

Sure. Temporary tables are a hard issue (another place where they cause
trouble are 2PC transactions, IIRC), so I think it's perfectly sensible to
accept the limitation, handle cases that we can handle and see if we can
improve the remaining cases later.

>
>
>>
>>>If Postgres backend is able to work only with on database, then 
>>>you will have to start at least such number of backends as number 
>>>of databases you have.
>>>implement multiuser access to the same backend (as it can be done 
>>>now using "set role").
>>>

Yes, that's a direct consequence of the PostgreSQL process model.

>attempt to bind backends to database and reuse them.

I'm not sure I understand. Surely we'd still reuse connections as much as
possible - we'd still keep the per-db/user connection pools, but after
running out of backend connections we'd pick a victim in one of the pools,
close it and open a new connection.

We'd need some logic for picking the 'victim' but that does not seem
particularly hard - idle connections first, then connections from
"oversized" pools (this is one of the reasons why pgbouncer has
min_connection_pool).

>But I suspect many problems with reusing pgbouncer code and moving it 
>to Postgres core.
>

To be clear - I wasn't suggesting to copy any code from pgbouncer. It's
far too different (style, ...) compared to core. I'm suggesting to adopt
roughly the same configuration approach, i.e. what parameters are allowed
for each pool, global limits, etc.

I don't know whether we should have a separate configuration file, make it
part of pg_hba.conf somehow, or store the configuration in a system
catalog. But I'm pretty sure we don't need a "sophisticated configurator".

>>>As far as pooler is done at transaction level, all non-active 
>>>session are in idle state
>The only difference is that them are still connected with client 
>though proxy.
>What I wanted to say is that pg_stat_activity will show you 
>information about all active transactions

I suggest you take a look at metrics used for pgbouncer monitoring. Even
when you have pending connection, you can still get useful data about that
(e.g. average wait time to get a backend, maximum wait time, ...).

Furthermore, how will you know from pg_stat_activity whether a connection
is coming through a connection pool or not? Or that it's (not) tainted? Or
how many backends are used by all connection pools combined?

Because those are questions people will be asking when investigating
issues, and so on.

regards

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 31 Jul 2019 11:39:47 +0300

> > parameter which allows to terminate idle workers.

I have implemented idle_pool_worker_timeout.
Also I added _idle_clients and n_idle_backends fields to proxy statistic 
returned by pg_pooler_state() function.

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 84341a3..acd7041 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -719,6 +719,137 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-idle-pool-worker-timeout" xreflabel="idle_pool_worker_timeout">
+      <term><varname>idle_pool_worker_timeout</varname> (<type>integer</type>)
+       <primary><varname>idle_pool_worker_timeout</varname> configuration parameter</primary>
+         Terminate an idle connection pool worker after the specified number of milliseconds.
+         The default value is 0, so pool workers are never terminated.
index 0000000..bc6547b
+    be possible to drop database to which they are connected.  It can be achieved without server restart using <varname>restart_pooler_on_reload</varname> variable. Setting this variable to <literal>true</literal> cause shutdown of all pooled backends after execution of <function>pg_reload_conf()</function> function. Then it will be possible to drop database. Alternatively you can specify <varname>idle-pool-worker-timeout</varname> which
+    forces termination of workers not used for the specified time. If database is not accessed for a long time, then all pool workers are terminated.

 

+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

index 0000000..57e3ba5
@@ -0,0 +1,1156 @@
+#include "utils/timestamp.h"
+	TimestampTz backend_last_activity;   /* time of last backend activity */
+	TimestampTz last_idle_timeout_check;  /* Time of last check for idle worker timeout expration */
+			chan->pool->proxy->state->n_idle_clients += 1;
+			chan->pool->proxy->state->n_idle_backends += 1;
+	chan->pool->proxy->state->n_idle_clients += 1;
+	chan->pool->proxy->state->n_idle_clients -= 1;
+		chan->pool->proxy->state->n_idle_backends -= 1;
+		if (IdlePoolWorkerTimeout)
+			chan->backend_last_activity = GetCurrentTimestamp();
+				if (IdlePoolWorkerTimeout)
+					idle_backend->backend_last_activity = GetCurrentTimestamp();
+		for (ipp = &chan->pool->pending_clients; *ipp != NULL; ipp = &(*ipp)->next)
+			if (*ipp == chan)
+		if (!peer)
+			chan->pool->proxy->state->n_idle_clients -= 1;
+		for (ipp = &chan->pool->idle_backends; *ipp != NULL; ipp = &(*ipp)->next)
+			if (*ipp == chan)
+				chan->pool->proxy->state->n_idle_backends -= 1;
+		int wait_timeout = IdlePoolWorkerTimeout ? IdlePoolWorkerTimeout : PROXY_WAIT_TIMEOUT;
+		n_ready = WaitEventSetWait(proxy->wait_events, wait_timeout, ready, MAX_READY_EVENTS, PG_WAIT_CLIENT);
+		if (IdlePoolWorkerTimeout)
+			TimestampTz now = GetCurrentTimestamp();
+			TimestampTz timeout_usec = IdlePoolWorkerTimeout*1000;
+			if (proxy->last_idle_timeout_check + timeout_usec < now)
+				HASH_SEQ_STATUS seq;
+				proxy->last_idle_timeout_check = now;
+				hash_seq_init(&seq, proxy->pools);
+				while ((pool = hash_seq_search(&seq)) != NULL)
+					for (chan = pool->idle_backends; chan != NULL; chan = chan->next)
+						if (chan->backend_last_activity + timeout_usec < now)
+							chan->is_interrupted = true; /* interrupted flags makes channel_write to send 'X' message */
+	Datum values[11];
+	bool  nulls[11];
+	values[6] = Int32GetDatum(ProxyState[id].n_idle_backends);
+	values[7] = Int32GetDatum(ProxyState[id].n_idle_clients);
+	values[8] = Int64GetDatum(ProxyState[id].tx_bytes);
+	values[9] = Int64GetDatum(ProxyState[id].rx_bytes);
+	values[10] = Int64GetDatum(ProxyState[id].n_transactions);
+	for (i = 0; i <= 11; i++)

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

index 3bf96de..b128b9c 100644
@@ -130,9 +130,15 @@ int			max_parallel_maintenance_workers = 2;
+int			IdlePoolWorkerTimeout = 0;
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 10;
@@ -148,3 +154,4 @@ int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
 
index 92c4fee..24b0d22 100644

 /*
 
 	{
@@ -2138,6 +2156,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
+		/* see max_connections and max_wal_senders */
+		{"session_pool_size", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets number of backends serving client sessions."),
+			gettext_noop("If non-zero then session pooling will be used: "
+						 "client connections will be redirected to one of the backends and maximal number of backends is determined by this parameter."
+						 "Launched backend are never terminated even in case of no active sessions.")
+		},
+		&SessionPoolSize,
+		10, 0, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"idle_pool_worker_timeout", PGC_USERSET, CONN_POOLING,
+			gettext_noop("Sets the maximum allowed duration of any idling connection pool worker."),
+			gettext_noop("A value of 0 turns off the timeout."),
+			GUC_UNIT_MS
+		},
+		&IdlePoolWorkerTimeout,
+		0, 0, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"connection_proxies", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets number of connection proxies."),
+			gettext_noop("Postmaster spawns separate worker process for each proxy. Postmaster scatters connections between proxies using one of scheduling policies (round-robin, random, load-balancing)."
+						 "Each proxy launches its own subset of backends. So maximal number of non-tainted backends is "
+						 "session_pool_size*connection_proxies*databases*roles.")
+		},
+		&ConnectionProxiesNumber,
+		0, 0, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"max_sessions", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Sets the maximum number of client session."),
+			gettext_noop("Maximal number of client sessions which can be handled by ont connection proxy."
+						 "It can be greater than max_connections and actually be arbitrary large.")
+		},
+		&MaxSessions,
+		1000, 1, INT_MAX,
+		NULL, NULL, NULL
+	},
+
+	{
 		/* see max_connections */
 		{"superuser_reserved_connections", PGC_POSTMASTER, CONN_AUTH_SETTINGS,
 			gettext_noop("Sets the number of connection slots reserved for superusers."),
@@ -2185,6 +2250,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2254,7 +2329,7 @@ static struct config_int ConfigureNamesInt[] =
 
 	/*
@@ -4550,6 +4625,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -4561,7 +4646,7 @@ static struct config_enum ConfigureNamesEnum[] =
 
 /*
@@ -4747,7 +4832,7 @@ extra_field_used(struct config_generic *gconf, void *extra)
 }
 
 /*
- * Support for assigning to an "extra" field of a GUC item.  Free the prior
+ * Support for assigning to an "extra" field of a GUC item.	 Free the prior
  * value if it's not referenced anywhere else in the item (including stacked
  * states).
  */
@@ -4837,7 +4922,7 @@ get_guc_variables(void)

 /*
@@ -5011,7 +5096,7 @@ add_placeholder_variable(const char *name, int elevel)
 
 	/*
@@ -5027,7 +5112,7 @@ add_placeholder_variable(const char *name, int elevel)
 }
 
 /*
@@ -5053,7 +5138,7 @@ find_option(const char *name, bool create_placeholders, int elevel)
 		return *res;
 
 	/*
-	 * See if the name is an obsolete name for a variable.  We assume that the
+	 * See if the name is an obsolete name for a variable.	We assume that the
 	 * set of supported old names is short enough that a brute-force search is
 	 * the best way.
 	 */
@@ -5414,7 +5499,7 @@ SelectConfigFiles(const char *userDoption, const char *progname)
 	}
 
 	/*
@@ -5709,7 +5794,7 @@ AtStart_GUC(void)
@@ -5733,10 +5818,10 @@ NewGUCNestLevel(void)
@@ -6067,7 +6152,7 @@ ReportGUCOption(struct config_generic *record)
 
 /*
@@ -6130,7 +6215,7 @@ convert_to_base_unit(double value, const char *unit,
@@ -6764,7 +6849,7 @@ set_config_option(const char *name, const char *value,
 
 	/*
@@ -6806,7 +6891,7 @@ set_config_option(const char *name, const char *value,
@@ -6868,7 +6953,7 @@ set_config_option(const char *name, const char *value,
@@ -6915,9 +7000,9 @@ set_config_option(const char *name, const char *value,
@@ -7490,7 +7575,7 @@ set_config_sourcefile(const char *name, char *sourcefile, int sourceline)
@@ -7696,7 +7781,7 @@ flatten_set_variable_args(const char *name, List *args)
 
 		if (l != list_head(args))
 			appendStringInfoString(&buf, ", ");
@@ -7753,7 +7838,7 @@ flatten_set_variable_args(const char *name, List *args)
 				else
 				{
 					/*
-					 * Plain string literal or identifier.  For quote mode,
+					 * Plain string literal or identifier.	For quote mode,
 					 * quote it if it's not a vanilla identifier.
 					 */
 					if (flags & GUC_LIST_QUOTE)
@@ -8034,7 +8119,7 @@ AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
 
 	/*
@@ -8092,7 +8177,7 @@ AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt)
 						AutoConfTmpFileName)));
 
 	/*
@@ -8146,6 +8231,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
+		MyProc->is_tainted = true;
+
 	switch (stmt->kind)
 	{
 		case VAR_SET_VALUE:
@@ -8175,7 +8263,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)

 					if (strcmp(item->defname, "transaction_isolation") == 0)
 						SetPGVariable("transaction_isolation",
@@ -8197,7 +8285,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)

@@ -8215,7 +8303,7 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
 				if (stmt->is_local)
 					ereport(ERROR,
@@ -8369,7 +8457,7 @@ init_custom_variable(const char *name,
 	/*
@@ -8378,7 +8466,7 @@ init_custom_variable(const char *name,
@@ -8460,9 +8548,9 @@ define_custom_variable(struct config_generic *variable)
 
@@ -8488,7 +8576,7 @@ define_custom_variable(struct config_generic *variable)
 	/*
@@ -8566,9 +8654,9 @@ reapply_stacked_values(struct config_generic *variable,
@@ -9279,7 +9367,7 @@ show_config_by_name(PG_FUNCTION_ARGS)
 
 /*
@@ -9433,7 +9521,7 @@ show_all_settings(PG_FUNCTION_ARGS)
@@ -9661,7 +9749,7 @@ _ShowOption(struct config_generic *record, bool use_units)
 
 /*
@@ -9896,14 +9984,14 @@ read_nondefault_variables(void)
@@ -9952,7 +10040,7 @@ estimate_variable_size(struct config_generic *gconf)
 
 				/*
@@ -9968,7 +10056,7 @@ estimate_variable_size(struct config_generic *gconf)
@@ -10324,7 +10412,7 @@ ParseLongOption(const char *string, char **name, char **value)
 
 /*
@@ -10383,7 +10471,7 @@ ProcessGUCArray(ArrayType *array,

 /*
- * Add an entry to an option array.  The array parameter may be NULL
+ * Add an entry to an option array.	 The array parameter may be NULL
  * to indicate the current table entry is NULL.
  */
 ArrayType *
@@ -10463,7 +10551,7 @@ GUCArrayAdd(ArrayType *array, const char *name, const char *value)
 
 /*
@@ -10604,8 +10692,8 @@ GUCArrayReset(ArrayType *array)
@@ -10627,13 +10715,13 @@ validate_option_array_item(const char *name, const char *value,
@@ -10686,7 +10774,7 @@ validate_option_array_item(const char *name, const char *value,
@@ -11122,7 +11210,7 @@ check_canonical_path(char **newval, void **extra, GucSource source)
@@ -11135,7 +11223,7 @@ check_timezone_abbreviations(char **newval, void **extra, GucSource source)
@@ -11173,7 +11261,7 @@ assign_timezone_abbreviations(const char *newval, void *extra)
@@ -11203,7 +11291,7 @@ assign_tcp_keepalives_idle(int newval, void *extra)
@@ -11491,11 +11579,11 @@ assign_recovery_target_timeline(const char *newval, void *extra)
 
 /*
index 8733524..a3773b4 100644
 
+  proallargtypes => '{int4,int4,int4,int4,int4,int4,int4,int4,int8,int8,int8}', proargmodes => '{o,o,o,o,o,o,o,o,o,o,o}',
+  proargnames => '{pid,n_clients,n_ssl_clients,n_pools,n_backends,n_dedicated_backends,n_idle_backends,n_idle_clients,tx_bytes,rx_bytes,n_transactions}', prosrc => 'pg_pooler_state' },
 
-#ifndef ENABLE_GSS
 
index 61a24c2..7a93bf4 100644
@@ -159,6 +159,20 @@ extern PGDLLIMPORT int data_directory_mode;
+extern PGDLLIMPORT int IdlePoolWorkerTimeout;

 

 

 
index 0000000..254d0f0
+	int n_idle_backends;      /* number of idle backends */
+	int n_idle_clients;       /* number of idle clients */

 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Fri, 2 Aug 2019 14:05:57 +0300

On 02.08.2019 12:57, DEV_OPS wrote:
> Hello Konstantin
>
>
> would you please re-base this patch? I'm going to test it, and back port
> into PG10 stable and PG9 stable
>
>
> thank you very much
>
>

Thank you.
Rebased patch is attached.

index c91e3e1..119daac 100644
 
index 3da2365..b82637e 100644
 
index c12b613..7d60c9b 100644
 
 	/* Shouldn't get a duplicate entry */
 	if (found)
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index fb2be10..5f2cd5f 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -591,6 +591,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));

 
+	if (FeBeWaitSet)
 
+

 

 
index 3339804..0d1df3c 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

index 0000000..156a91d
+	for (i = 0; i < 11; i++)

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);
 
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 1b7053c..b7c1ed7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -774,7 +774,10 @@ LockAcquireExtended(const LOCKTAG *locktag,
 
 	/* Identify owner for lock */
 	if (sessionLock)
+	{
 		owner = NULL;
+		MyProc->is_tainted = true;
+	}
 	else
 		owner = CurrentResourceOwner;
 
index a6505c7..e07f540 100644
@@ -4237,6 +4237,8 @@ PostgresMain(int argc, char *argv[],
index bc62c6e..6f1bb75 100644

 
index fc46360..abac1cd 100644

 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
 
+	if (!stmt->is_local)

 

 				if (stmt->is_local)
 					ereport(ERROR,

 /*
 
 /*
 
 				/*
 
 /*

 /*
 
 /*
 
 /*
index b88e886..812c469 100644
@@ -10704,4 +10704,11 @@
 
index 541f970..d739dc3 100644
 
-#ifndef ENABLE_GSS

 

 
 
index b692d8b..d301f8c 100644

@@ -62,6 +68,9 @@ extern Size ShmemBackendArraySize(void);

 
 typedef struct WaitEvent

 
 
index fcf2bc2..7f2a1df 100644
 
-#ifndef ENABLE_GSS

 
index d1d0aed..a677577 100644

+	my $libpqconn =

---

From: Ryan Lambert <[email-masked]>
Date: Tue, 6 Aug 2019 21:18:08 -0600

Hi Konstantin,

I did some testing with the latest patch [1] on a small local VM with 1 CPU
and 2GB RAM with the intention of exploring pg_pooler_state().

Configuration:

idle_pool_worker_timeout = 0 (default)
connection_proxies = 2
max_sessions = 10 (default)
max_connections = 1000

Initialized pgbench w/ scale 10 for the small server.

Running pgbench w/out connection pooler with 300 connections:

pgbench -p 5432 -c 300 -j 1 -T 60 -P 15 -S bench_test
starting vacuum...end.
progress: 15.0 s, 1343.3 tps, lat 123.097 ms stddev 380.780
progress: 30.0 s, 1086.7 tps, lat 155.586 ms stddev 376.963
progress: 45.1 s, 1103.8 tps, lat 156.644 ms stddev 347.058
progress: 60.6 s, 652.6 tps, lat 271.060 ms stddev 575.295
transaction type: <builtin: select only>
scaling factor: 10
query mode: simple
number of clients: 300
number of threads: 1
duration: 60 s
number of transactions actually processed: 63387
latency average = 171.079 ms
latency stddev = 439.735 ms
tps = 1000.918781 (including connections establishing)
tps = 1000.993926 (excluding connections establishing)

It crashes when I attempt to run with the connection pooler, 300
connections:

pgbench -p 6543 -c 300 -j 1 -T 60 -P 15 -S bench_test
starting vacuum...end.
connection to database "bench_test" failed:
server closed the connection unexpectedly
       This probably means the server terminated abnormally
       before or while processing the request.

In the logs I get:

WARNING:  PROXY: Failed to add new client - too much sessions: 18 clients,
1 backends. Try to increase 'max_sessions' configuration parameter.

The logs report 1 backend even though max_sessions is the default of 10.
Why is there only 1 backend reported?  Is that error message getting the
right value?

Minor grammar fix, the logs on this warning should say "too many sessions"
instead of "too much sessions."

Reducing pgbench to only 30 connections keeps it from completely crashing
but it still does not run successfully.

pgbench -p 6543 -c 30 -j 1 -T 60 -P 15 -S bench_test
starting vacuum...end.
client 9 aborted in command 1 (SQL) of script 0; perhaps the backend died
while processing
client 11 aborted in command 1 (SQL) of script 0; perhaps the backend died
while processing
client 13 aborted in command 1 (SQL) of script 0; perhaps the backend died
while processing
...
...
progress: 15.0 s, 5734.5 tps, lat 1.191 ms stddev 10.041
progress: 30.0 s, 7789.6 tps, lat 0.830 ms stddev 6.251
progress: 45.0 s, 8211.3 tps, lat 0.810 ms stddev 5.970
progress: 60.0 s, 8466.5 tps, lat 0.789 ms stddev 6.151
transaction type: <builtin: select only>
scaling factor: 10
query mode: simple
number of clients: 30
number of threads: 1
duration: 60 s
number of transactions actually processed: 453042
latency average = 0.884 ms
latency stddev = 7.182 ms
tps = 7549.373416 (including connections establishing)
tps = 7549.402629 (excluding connections establishing)
Run was aborted; the above results are incomplete.

Logs for that run show (truncated):

2019-08-07 00:19:37.707 UTC [22152] WARNING:  PROXY: Failed to add new
client - too much sessions: 18 clients, 1 backends. Try to increase
'max_sessions' configuration parameter.
2019-08-07 00:31:10.467 UTC [22151] WARNING:  PROXY: Failed to add new
client - too much sessions: 15 clients, 4 backends. Try to increase
'max_sessions' configuration parameter.
2019-08-07 00:31:10.468 UTC [22152] WARNING:  PROXY: Failed to add new
client - too much sessions: 15 clients, 4 backends. Try to increase
'max_sessions' configuration parameter.
...
...

Here it is reporting fewer clients with more backends. Still, only 4
backends reported with 15 clients doesn't seem right.  Looking at the
results from pg_pooler_state() at the same time (below) showed 5 and 7
backends for the two different proxies, so why are the logs only reporting
4 backends when pg_pooler_state() reports 12 total?

Why is n_idle_clients negative?  In this case it showed -21 and -17.  Each
proxy reported 7 clients, with max_sessions = 10, having those
n_idle_client results doesn't make sense to me.

postgres=# SELECT * FROM pg_pooler_state();
 pid  | n_clients | n_ssl_clients | n_pools | n_backends |
n_dedicated_backends | n_idle_backends | n_idle_clients | tx_bytes |
rx_bytes | n_transactions

-------+-----------+---------------+---------+------------+----------------------+-----------------+----------------+----------+----------+---------------
-
25737 |         7 |             0 |       1 |          5 |
   0 |               0 |            -21 |  4099541 |  3896792 |
 61959
25738 |         7 |             0 |       1 |          7 |
   0 |               2 |            -17 |  4530587 |  4307474 |
 68490
(2 rows)

I get errors running pgbench down to only 20 connections with this
configuration. I tried adjusting connection_proxies = 1 and it handles even
fewer connections.  Setting connection_proxies = 4 allows it to handle 20
connections without error, but by 40 connections it starts having issues.

While I don't have expectations of this working great (or even decent) on a
tiny server, I don't expect it to crash in a case where the standard
connections work.  Also, the logs and the function both show that the total
backends is less than the total available and the two don't seem to agree
on the details.

I think it would help to have details about the pg_pooler_state function
added to the docs, maybe in this section [2]?

I'll take some time later this week to examine pg_pooler_state further on a
more appropriately sized server.

Thanks,

[1]
https://www.postgresql.org/message-id/attachment/103046/builtin_connection_proxy-16.patch
[2] https://www.postgresql.org/docs/current/functions-info.html

Ryan Lambert

---

From: Li Japin <[email-masked]>
Date: Wed, 7 Aug 2019 04:21:41 +0000

Hi, Konstantin

I test the patch-16 on postgresql master branch, and I find the 
temporary table
cannot removed when we re-connect to it. Here is my test:

japin@ww-it:~/WwIT/postgresql/Debug/connpool$ initdb
The files belonging to this database system will be owned by user "japin".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory /home/japin/WwIT/postgresql/Debug/connpool/DATA ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting default time zone ... Asia/Shanghai
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

initdb: warning: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

     pg_ctl -D /home/japin/WwIT/postgresql/Debug/connpool/DATA -l 
logfile start

japin@ww-it:~/WwIT/postgresql/Debug/connpool$ pg_ctl -l /tmp/log start
waiting for server to start.... done
server started
japin@ww-it:~/WwIT/postgresql/Debug/connpool$ psql postgres
psql (13devel)
Type "help" for help.

postgres=# ALTER SYSTEM SET connection_proxies TO 1;
ALTER SYSTEM
postgres=# ALTER SYSTEM SET session_pool_size TO 1;
ALTER SYSTEM
postgres=# \q
japin@ww-it:~/WwIT/postgresql/Debug/connpool$ pg_ctl -l /tmp/log restart
waiting for server to shut down.... done
server stopped
waiting for server to start.... done
server started
japin@ww-it:~/WwIT/postgresql/Debug/connpool$ psql -p 6543 postgres
psql (13devel)
Type "help" for help.

postgres=# CREATE TEMP TABLE test(id int, info text);
CREATE TABLE
postgres=# INSERT INTO test SELECT id, md5(id::text) FROM 
generate_series(1, 10) id;
INSERT 0 10
postgres=# select * from pg_pooler_state();
  pid  | n_clients | n_ssl_clients | n_pools | n_backends | 
n_dedicated_backends | n_idle_backends | n_idle_clients | tx_bytes | 
rx_bytes | n_transactions
------+-----------+---------------+---------+------------+----------------------+-----------------+----------------+----------+----------+----------------
  3885 |         1 |             0 |       1 |          1 
|                    0 |               0 |              0 | 1154 |     
2880 |              6
(1 row)

postgres=# \q
japin@ww-it:~/WwIT/postgresql/Debug/connpool$ psql -p 6543 postgres
psql (13devel)
Type "help" for help.

postgres=# \d
         List of relations
   Schema   | Name | Type  | Owner
-----------+------+-------+-------
  pg_temp_3 | test | table | japin
(1 row)

------+-----------+---------------+---------+------------+----------------------+-----------------+----------------+----------+----------+----------------
  3885 |         1 |             0 |       1 |          1 
|                    0 |               0 |              0 | 2088 |     
3621 |              8
(1 row)

postgres=# select * from test ;
  id |               info
----+----------------------------------
   1 | c4ca4238a0b923820dcc509a6f75849b
   2 | c81e728d9d4c2f636f067f89cc14862c
   3 | eccbc87e4b5ce2fe28308fd9f2a7baf3
   4 | a87ff679a2f3e71d9181a67b7542122c
   5 | e4da3b7fbbce2345d7772b0674a318d5
   6 | 1679091c5a880faf6fb5e6087eb1b2dc
   7 | 8f14e45fceea167a5a36dedd4bea2543
   8 | c9f0f895fb98ab9159f51fd0297e236d
   9 | 45c48cce2e2d7fbdea1afc51c7c6ad26
  10 | d3d9446802a44259755d38e6d163e820
(10 rows)

I inspect the code, and find the following code in DefineRelation function:

if (stmt->relation->relpersistence != RELPERSISTENCE_TEMP
         && stmt->oncommit != ONCOMMIT_DROP)
         MyProc->is_tainted = true;

For temporary table, MyProc->is_tainted might be true, I changed it as 
following:

if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
         || stmt->oncommit == ONCOMMIT_DROP)
         MyProc->is_tainted = true;

For temporary table, it works. I not sure the changes is right.

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 7 Aug 2019 10:49:12 +0300

Hi, Li

Thank you very much for reporting the problem.

> For temporary table, it works. I not sure the changes is right.
Sorry, it is really a bug.
My intention was to mark backend as tainted if it is creating temporary 
table without ON COMMIT DROP clause (in the last case temporary table 
will be local to transaction and so cause no problems with pooler).
Th right condition is:

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 7 Aug 2019 13:57:27 +0300

Hi Ryan,

On 07.08.2019 6:18, Ryan Lambert wrote:
> Hi Konstantin,
>
> I did some testing with the latest patch [1] on a small local VM with 
> 1 CPU and 2GB RAM with the intention of exploring pg_pooler_state().
>
> Configuration:
>
> WARNING:  PROXY: Failed to add new client - too much sessions: 18 
> clients, 1 backends. Try to increase 'max_sessions' configuration 
> parameter.
>
> The logs report 1 backend even though max_sessions is the default of 
> 10.  Why is there only 1 backend reported?  Is that error message 
> getting the right value?
>
> Minor grammar fix, the logs on this warning should say "too many 
> sessions" instead of "too much sessions."
>
> Reducing pgbench to only 30 connections keeps it from completely 
> crashing but it still does not run successfully.
>
> client 9 aborted in command 1 (SQL) of script 0; perhaps the backend 
> died while processing
> client 11 aborted in command 1 (SQL) of script 0; perhaps the backend 
> died while processing
> client 13 aborted in command 1 (SQL) of script 0; perhaps the backend 
> died while processing
> ...
> ...
> backends for the two different proxies, so why are the logs only 
> reporting 4 backends when pg_pooler_state() reports 12 total?
>
> Why is n_idle_clients negative?  In this case it showed -21 and -17.  
> Each proxy reported 7 clients, with max_sessions = 10, having those 
> configuration. I tried adjusting connection_proxies = 1 and it handles 
> even fewer connections.  Setting connection_proxies = 4 allows it to 
> handle 20 connections without error, but by 40 connections it starts 
> having issues.
>
> While I don't have expectations of this working great (or even decent) 
> on a tiny server, I don't expect it to crash in a case where the 
> standard connections work.  Also, the logs and the function both show 
> that the total backends is less than the total available and the two 
> don't seem to agree on the details.
>
> I think it would help to have details about the pg_pooler_state 
> function added to the docs, maybe in this section [2]?
>
> I'll take some time later this week to examine pg_pooler_state further 
> on a more appropriately sized server.
>
> Thanks,
>
>
> [1] 

Sorry, looks like there is misunderstanding with meaning of max_sessions 
parameters.
First of all default value of this parameter is 1000, not 10.
Looks like you have explicitly specify value 10 and it cause this problems.

So "max_sessions" parameter specifies how much sessions can be handled 
by one backend.
Certainly it makes sense only if pooler is switched on (number of 
proxies is not zero).
If pooler is switched off, than backend is handling exactly one session/

There is no much sense in limiting number of sessions server by one 
backend, because the main goal of connection pooler is to handle arbitrary
number of client connections with limited number of backends.
The only reason for presence of this parameter is that WaitEventSet 
requires to specify maximal number of events.
And proxy needs to multiplex connected backends and clients. So it 
create WaitEventSet with size max_sessions*2 (mutiplied by two because 
it has to listen both for clients and backends).

So the value of this parameter should be large enough. Default value is 
1000, but there should be no problem to set it to 10000 or even 1000000 
(hoping that IS will support it).

But observer behavior ("server closed the connection unexpectedly" and 
hegative number of idle clients) is certainly not correct.
I attached to this mail patch which is fixing both problems: correctly 
reports error to the client and calculates  number of idle clients).
New version also available in my GIT repoistory: 
https://github.com/postgrespro/postgresql.builtin_pool.git
branch conn_proxy.

diff --git a/contrib/spi/refint.c b/contrib/spi/refint.c
index adf0490..5c2095f 100644
--- a/contrib/spi/refint.c
+++ b/contrib/spi/refint.c
@@ -11,6 +11,7 @@
 
 #include "commands/trigger.h"
 #include "executor/spi.h"
+#include "storage/proc.h"
 #include "utils/builtins.h"
 #include "utils/rel.h"
 
@@ -93,6 +94,8 @@ check_primary_key(PG_FUNCTION_ARGS)
 	else
 		tuple = trigdata->tg_newtuple;
 
+	MyProc->is_tainted = true;
+
 	trigger = trigdata->tg_trigger;
 	nargs = trigger->tgnargs;
 	args = trigger->tgargs;
@@ -284,6 +287,8 @@ check_foreign_key(PG_FUNCTION_ARGS)
 		/* internal error */
 		elog(ERROR, "check_foreign_key: cannot process INSERT events");
 
+	MyProc->is_tainted = true;
+
 	/* Have to check tg_trigtuple - tuple being deleted */
 	trigtuple = trigdata->tg_trigtuple;

 
 <!-- administrator's guide -->
 <!ENTITY backup        SYSTEM "backup.sgml">
diff --git a/doc/src/sgml/postgres.sgml b/doc/src/sgml/postgres.sgml
index 3e115f1..ee6e2bd 100644
--- a/doc/src/sgml/postgres.sgml
+++ b/doc/src/sgml/postgres.sgml
@@ -158,6 +158,7 @@
   &maintenance;
   &backup;
   &high-availability;
+  &connpool;
   &monitoring;
   &diskusage;
   &wal;
diff --git a/src/Makefile b/src/Makefile
index bcdbd95..196ca8c 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -23,6 +23,7 @@ SUBDIRS = \
 	interfaces \
 	backend/replication/libpqwalreceiver \
 	backend/replication/pgoutput \
+	backend/postmaster/libpqconn \
 	fe_utils \
 	bin \
 	pl \
diff --git a/src/backend/commands/portalcmds.c b/src/backend/commands/portalcmds.c
index 83f9959..cf7d1dd 100644
--- a/src/backend/commands/portalcmds.c
+++ b/src/backend/commands/portalcmds.c
@@ -28,6 +28,7 @@
 #include "executor/executor.h"
 #include "executor/tstoreReceiver.h"
 #include "rewrite/rewriteHandler.h"
+#include "storage/proc.h"
 #include "tcop/pquery.h"
 #include "tcop/tcopprot.h"
 #include "utils/memutils.h"
@@ -57,6 +58,8 @@ PerformCursorOpen(DeclareCursorStmt *cstmt, ParamListInfo params,
 				(errcode(ERRCODE_INVALID_CURSOR_NAME),
 				 errmsg("invalid cursor name: must not be empty")));
 
+	MyProc->is_tainted = true; /* cursors are not compatible with builtin connection pooler */
+
 	/*
 	 * If this is a non-holdable cursor, we require that this statement has
 	 * been executed inside a transaction block (or else, it would have no
 
 	/* Shouldn't get a duplicate entry */
 	if (found)
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index 0960b33..ac51dc4 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -251,6 +251,19 @@ DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
 	heap_freetuple(tuple);
 	table_close(rel, RowExclusiveLock);
 
+	/*
+	 * TODO:
+	 * Using currval() may cause incorrect behaviour with connectoin pooler.
+	 * Unfortunately makring backend as tainted in currval() is too late.
+	 * This is why it is done in nextval(), althougth it is not strictly required, because
+	 * nextval() may be not followed by currval().
+	 * But currval() may be not preceeded by nextval().
+	 * To make regression tests passed, backend is also marker ias tainted when it creates
+	 * sequence. Certainly it is just temoporary workaround, because sequence may be created
+	 * in one backend and accessed in another.
+	 */
+	MyProc->is_tainted = true; /* in case of using currval() */
+
 	return address;
 }
 
@@ -564,6 +577,8 @@ nextval(PG_FUNCTION_ARGS)
 	 */
 	relid = RangeVarGetRelid(sequence, NoLock, false);
 
+	MyProc->is_tainted = true; /* in case of using currval() */
+
 	PG_RETURN_INT64(nextval_internal(relid, true));
 }
 
index fb2be10..b0af84b 100644
 
+	if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP

+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

index 0000000..a8d7322
@@ -0,0 +1,1177 @@
+	bool     is_idle;            /* no activity on this channel */
+			chan->peer->is_idle = true;
+			chan->is_idle = true;
+	chan->is_idle = true;
+ * Send error message to the client. This function is called when new backend can not be started
+ * or client is assigned to the backend because of configuration limitations.
+report_error_to_client(Channel* chan, char const* error)
+	chan->is_idle = false;
+		idle_backend->is_idle = false;
+					report_error_to_client(chan, error);
+		if (chan->is_idle)
+			chan->is_idle = false;
+				Assert (chan->is_idle);
+				chan->is_idle = false;
+		*error = strdup("Too much sessios: try to increase 'max_sessions' configuration parameter");
+		report_error_to_client(chan, "Too much sessions. Try to increase 'max_sessions' configuration parameter");

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
 
+	if (!stmt->is_local)

 

 				if (stmt->is_local)
 					ereport(ERROR,

 /*
 
 /*
 
 				/*
 
 /*

 /*
 
 /*
 
 /*

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Ryan Lambert <[email-masked]>
Date: Wed, 7 Aug 2019 06:52:26 -0600

> First of all default value of this parameter is 1000, not 10.

Oops, my bad!  Sorry about that, I'm not sure how I got that in my head
last night but I see how that would make it act strange now.  I'll adjust
my notes before re-testing. :)

Thanks,

*Ryan Lambert*

---

From: Ryan Lambert <[email-masked]>
Date: Wed, 7 Aug 2019 20:48:59 -0600

> reports error to the client and calculates  number of idle clients).

Yes, this works much better with max_sessions=1000.  Now it's handling the
300 connections on the small server.   n_idle_clients now looks accurate
with the rest of the stats here.

postgres=# SELECT n_clients, n_backends, n_idle_backends, n_idle_clients
FROM pg_pooler_state();
 n_clients | n_backends | n_idle_backends | n_idle_clients
-----------+------------+-----------------+----------------
       150 |         10 |               9 |            149
       150 |         10 |               6 |            146

Ryan Lambert

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 13 Aug 2019 18:04:52 +0300

Updated version of the patch is attached.
I rewrote  edge-triggered mode emulation and have tested it at MacOS/X.
So right now three major platforms: Linux, MaxOS and Windows are covered.
In theory it should work on most of other Unix dialects.

 

 

 

 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 
 
index 0000000..6ea4f35
+	char		c_buffer[CMSG_LEN(sizeof(sock))];
+	char		m_buffer[1];

 

 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 	/*
 
 /*
+ * StartProxyWorker

 

index 0000000..5f19ad6
@@ -0,0 +1,1174 @@
+	bool	 edge_triggered;	 /* emulate epoll EPOLLET (edge-triggered) flag */
+	if (chan->is_disconnected || chan->pool == NULL)
+		if (rc > 0 && chan->edge_triggered)
+			ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_WRITEABLE|WL_SOCKET_READABLE|WL_SOCKET_EDGE, NULL);
+			chan->edge_triggered = false;
+		else if (chan->edge_triggered)
+			chan->edge_triggered = false;
+					if (chan->peer == NULL || chan->peer->tx_size == 0) /* nothing to write */
+						/* At systems not supporting epoll edge triggering (Win32, FreeBSD, MacOS), we need to disable writable event to avoid busy loop */
+						chan->edge_triggered = true;
+					if (chan->tx_size != 0) /* pending write: read is not prohibited */
+						/* At systems not supporting epoll edge triggering (Win32, FreeBSD, MacOS), we need to disable readable event to avoid busy loop */
+						ModifyWaitEvent(chan->proxy->wait_events, chan->event_pos, WL_SOCKET_WRITEABLE | WL_SOCKET_EDGE, NULL);
+						chan->edge_triggered = true;

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 

 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 /*
 
 	{
 
 	{
 
 	{
 
 	/*
 
+	{
 
 /*
 
 /*

 /*
 
 	/*
 
 /*
 
 	/*
 
 	/*
 
 /*
 
 	/*

 	/*
 
 	/*
 
+	if (!stmt->is_local)

 

 				if (stmt->is_local)
 					ereport(ERROR,

 /*
 
 /*
 
 				/*
 
 /*

 /*
 
 /*
 
 /*

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 15 Aug 2019 14:01:26 +0300

>>> temporary table, is there a reason to still treat the session as 

I have implemented one more trick reducing number of tainted backends:
now it is possible to use session variables in pooled backends.

How it works?
Proxy determines "SET var=" statements and  converts them to "SET LOCAL 
var=".
Also all such assignments are concatenated and stored in session context 
at proxy.
Then proxy injects this statement inside each transaction block or 
prepend to standalone statements.

This mechanism works only for GUCs set outside transaction.
By default it is switched off. To enable it you should switch on 
"proxying_gucs" parameter.

 

 
 
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index c91e3e1..7aaddfe 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -719,6 +719,153 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+      <term><varname>restart_pooler_on_reload</varname> (<type>boolean</type>)
+     <varlistentry id="guc-proxying-gucs" xreflabel="proxying_gucs">
+      <term><varname>proxying_gucs</varname> (<type>boolean</type>)
+       <primary><varname>rproxying_gucs</varname> configuration parameter</primary>
+          Support setting parameters in connection pooler sessions.
+          When this parameter is switched on, setting session parameters are replaced with setting local (transaction) parameters,
+          which are concatenated with each transaction or stanalone statement. It make it possible not to mark backend as tainted.
index 0000000..899fd1c
@@ -0,0 +1,175 @@
+    (changing values of session variables (GUCs), creating temporary tables, preparing statements, advisory locking),
+    Switching on <varname>proxying_gucs</varname> configuration option allows to set sessions parameters without marking backend as <emphasis>tainted</emphasis>.

 
 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 
index 3339804..739b8fd 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }
 
@@ -5526,6 +5711,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
@@ -6116,6 +6369,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6347,6 +6604,9 @@ restore_backend_variables(BackendParameters *param, Port *port)
 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);

index 0000000..c28cefd
@@ -0,0 +1,1263 @@
+	bool     in_transaction;     /* inside transaction body */
+	char*    gucs;               /* concatenated "SET var=" commands for this session */
+	char*    prev_gucs;          /* previous value of "gucs" to perform rollback in case of error */
+	MemoryContext parse_ctx;	 /* Temporary memory context used for parsing startup packet */
+	MemoryContext proxy_ctx;
+	/* parse startup packet in parse_ctx memory context and reset it when it is not needed any more */
+	MemoryContextReset(chan->proxy->parse_ctx);
+	proxy_ctx = MemoryContextSwitchTo(chan->proxy->parse_ctx);
+	if (ParseStartupPacket(chan->client_port, chan->proxy->parse_ctx, startup_packet+4, startup_packet_size-4, false) != STATUS_OK) /* skip packet size */
+		MemoryContextSwitchTo(proxy_ctx);
+	MemoryContextSwitchTo(proxy_ctx);
+is_transaction_start(char* stmt)
+	return pg_strncasecmp(stmt, "begin", 5) == 0 || pg_strncasecmp(stmt, "start", 5) == 0;
+			uint32 new_msg_len;
+				chan->buf = repalloc(chan->buf, chan->buf_size);
+				else if (!chan->client_port) /* Message from backend */
+					if (chan->buf[msg_start] == 'Z'	/* Ready for query */
+							chan->peer->in_transaction = false;
+					else if (chan->buf[msg_start] == 'E')	/* Error */
+						if (chan->peer && chan->peer->prev_gucs)
+							/* Undo GUC assignment */
+							pfree(chan->peer->gucs);
+							chan->peer->gucs = chan->peer->prev_gucs;
+							chan->peer->prev_gucs = NULL;
+				else if (chan->client_port) /* Message from client */
+					if (chan->buf[msg_start] == 'X')	/* Terminate message */
+					else if (ProxyingGUCs && chan->buf[msg_start] == 'Q' && !chan->in_transaction)
+						char* stmt = &chan->buf[msg_start+5];
+						if (chan->prev_gucs)
+							pfree(chan->prev_gucs);
+							chan->prev_gucs = NULL;
+						if (pg_strncasecmp(stmt, "set", 3) == 0
+							&& pg_strncasecmp(stmt+3, " local", 6) != 0)
+							char* new_msg;
+							chan->prev_gucs = chan->gucs ? chan->gucs : pstrdup("");
+							chan->gucs = psprintf("%sset local%s%c", chan->prev_gucs, stmt+3,
+												  chan->buf[chan->rx_pos-2] == ';' ? ' ' : ';');
+							new_msg = chan->gucs + strlen(chan->prev_gucs);
+							Assert(msg_start + strlen(new_msg)*2 + 6 < chan->buf_size);
+							 * We need to send SET command to check if it is correct.
+							 * To avoid "SET LOCAL can only be used in transaction blocks"
+							 * error we need to construct block. Let's just double the command.
+							msg_len = sprintf(stmt, "%s%s", new_msg, new_msg) + 6;
+							new_msg_len = pg_hton32(msg_len - 1);
+							memcpy(&chan->buf[msg_start+1], &new_msg_len, sizeof(new_msg_len));
+							chan->rx_pos = msg_start + msg_len;
+						else if (chan->gucs)
+							size_t gucs_len = strlen(chan->gucs);
+							if (chan->rx_pos + gucs_len > chan->buf_size)
+								/* Reallocate buffer to fit concatenated GUCs */
+								chan->buf_size = chan->rx_pos + gucs_len;
+								chan->buf = repalloc(chan->buf, chan->buf_size);
+							if (is_transaction_start(stmt))
+								/* Append GUCs after BEGIN command to include them in transaction body */
+								memcpy(&chan->buf[chan->rx_pos-1], chan->gucs, gucs_len+1);
+								chan->in_transaction = true;
+								/* Prepend standalone command with GUCs */
+								memmove(stmt + gucs_len, stmt, msg_len);
+								memcpy(stmt, chan->gucs, gucs_len);
+							chan->rx_pos += gucs_len;
+							msg_len += gucs_len;
+							new_msg_len = pg_hton32(msg_len - 1);
+							memcpy(&chan->buf[msg_start+1], &new_msg_len, sizeof(new_msg_len));
+						else if (is_transaction_start(stmt))
+							chan->in_transaction = true;
+	Channel* chan = (Channel*)palloc0(sizeof(Channel));
+	chan->buf = palloc(INIT_BUF_SIZE);
+	chan->handshake_response = palloc(chan->handshake_response_size);
+		pfree(chan->buf);
+		pfree(chan);
+		pfree(port->gss);
+		pfree(port);
+		pfree(chan->buf);
+		pfree(chan);
+		pfree(chan->client_port);
+		if (chan->gucs)
+			pfree(chan->gucs);
+		if (chan->prev_gucs)
+			pfree(chan->prev_gucs);
+		pfree(chan->handshake_response);
+	pfree(chan->buf);
+	pfree(chan);
+	MemoryContext proxy_memctx = AllocSetContextCreate(TopMemoryContext,
+	MemoryContextSwitchTo(proxy_memctx);
+	proxy = palloc0(sizeof(Proxy));
+	proxy->parse_ctx = AllocSetContextCreate(proxy_memctx,
+	ctl.hcxt = proxy_memctx;
+				Port* port = (Port*)palloc0(sizeof(Port));
+					pfree(port);
+					port->gss = (pg_gssinfo *)palloc0(sizeof(pg_gssinfo));

 	/*
index 2426cbc..287fb19 100644

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 
 
index 3bf96de..aab2976 100644
+int			ConnectionProxiesNumber = 0;
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 10;
@@ -148,3 +154,5 @@ int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
 
 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
+bool        ProxyingGUCs = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index fc46360..dc2e5f9 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -457,6 +457,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
@@ -1286,6 +1294,26 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
+		{"restart_pooler_on_reload", PGC_SIGHUP, CONN_POOLING,
+		 gettext_noop("Restart session pool workers on pg_reload_conf()."),
+		 NULL,
+		},
+		&RestartPoolerOnReload,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"proxying_gucs", PGC_USERSET, CONN_POOLING,
+		 gettext_noop("Support setting parameters in connection pooler sessions."),
+		 NULL,
+		},
+		&ProxyingGUCs,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
 		{"log_duration", PGC_SUSET, LOGGING_WHAT,
 			gettext_noop("Logs the duration of each completed SQL statement."),
 			NULL
@@ -2138,6 +2166,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2185,6 +2260,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4550,6 +4635,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8146,6 +8241,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS
 
index 61a24c2..a8e57f4 100644
@@ -159,6 +159,21 @@ extern PGDLLIMPORT int data_directory_mode;
+extern PGDLLIMPORT bool ProxyingGUCs;

 

 

 

 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Jaime Casanova <[email-masked]>
Date: Thu, 5 Sep 2019 17:01:01 -0500

> "proxying_gucs" parameter.

there is definitively something odd here. i applied the patch and
changed these parameters

connection_proxies = '3'
session_pool_size = '33'
port = '5433'
proxy_port = '5432'

after this i run "make installcheck", the idea is to prove if an
application going through proxy will behave sanely. As far as i
understood in case the backend needs session mode it will taint the
backend otherwise it will act as transaction mode.

Sadly i got a lot of FAILED tests, i'm attaching the diffs on
regression with installcheck and installcheck-parallel.
btw, after make installcheck-parallel i wanted to do a new test but
wasn't able to drop regression database because there is still a
subscription, so i tried to drop it and got a core file (i was
connected trough the pool_worker), i'm attaching the backtrace of the
crash too.

-- 
Jaime Casanova                      www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

---

From: Konstantin Knizhnik <[email-masked]>
Date: Fri, 6 Sep 2019 19:41:37 +0300

> connected trough the pool_worker), i'm attaching the backtrace of the

Thank you very much for testing connection pooler.
The problem with "make installcheck" is caused by GUCs passed by 
pg_regress inside startup packet:

     putenv("PGTZ=PST8PDT");
     putenv("PGDATESTYLE=Postgres, MDY");

Them are not currently handled by builtin proxy.
Just because I didn't find some acceptable solution for it.
With newly added proxying_gucs options it is possible, this problem is 
solved, but it leads to other problem:
some Postgres statements are not transactional and can not be used 
inside block.
As far as proxying_gucs appends gucs setting to the statement (and so 
implicitly forms transaction block),
such statement cause errors. I added check to avoid prepending GUCs 
settings to non-transactional statements.
But this check seems to be not so trivial. At least I failed to make it 
work: it doesn;t correctly handle specifying default namespace.

"make installcheck" can be passed if you add the folowing three settings 
to configuration file:

datestyle='Postgres, MDY'
timezone='PST8PDT'
intervalstyle='postgres_verbose'

Sorry, I failed to reproduce the crash.
So if you will be able to find out some scenario for reproduce it, I 
will be very pleased to receive it.

I attached to this main new version of the patch. It includes 
multitenancy support.
Before separate proxy instance is created for each <dbname,role> pair. 
Postgres backend is not able to work with more than one database.
But it is possible to change current user (role) inside one connection.
If "multitenent_proxy" options is switched on, then separate proxy will 
be create only for each database and current user is explicitly 
specified for each transaction/standalone
statement using "set command" clause.
To support this mode you need to grant permissions to all roles to 
switch between each other.

So basically multitenancy support uses the same mechanism as GUCs proxying.
I will continue work on improving GUCs proxying mechanism, so that it 
can pass regression tests.

 

 
 
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index c91e3e1..df0bcaf 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -719,6 +719,169 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
+       <primary><varname>proxying_gucs</varname> configuration parameter</primary>
+     <varlistentry id="guc-multitenant-proxy" xreflabel="multitenant_proxy">
+      <term><varname>multitenant_proxy</varname> (<type>boolean</type>)
+       <primary><varname>multitenant_proxy</varname> configuration parameter</primary>
+          One pool worker can serve clients with different roles.
+          When this parameter is switched on, each transaction or stanalone statement
+          are prepended with "set role" command.
index 0000000..8dc9594
@@ -0,0 +1,182 @@
+    As it was mentioned above separate proxy instance is created for each <literal>dbname,role</literal> pair. Postgres backend is not able to work with more than one database. But it is possible to change current user (role) inside one connection.
+    If <varname>multitenent_proxy</varname> options is switched on, then separate proxy
+    will be create only for each database and current user is explicitly specified for each transaction/standalone statement using <literal>set command<literal> clause.
+    To support this mode you need to grant permissions to all roles to switch between each other.

 
 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..07b866d
@@ -0,0 +1,1308 @@
+	if (MultitenantProxy)
+		chan->gucs = psprintf("set local role %s;", chan->client_port->user_name);
+	if (ProxyingGUCs)
+		ListCell *gucopts = list_head(chan->client_port->guc_options);
+		while (gucopts)
+			char	   *name;
+			char	   *value;
+			name = lfirst(gucopts);
+			gucopts = lnext(chan->client_port->guc_options, gucopts);
+			value = lfirst(gucopts);
+			gucopts = lnext(chan->client_port->guc_options, gucopts);
+			chan->gucs = psprintf("%sset local %s='%s';", chan->gucs ? chan->gucs : "", name, value);
+is_transactional_statement(char* stmt)
+	static char const* const non_tx_stmts[] = {
+		"create",
+		"cluster",
+		"drop",
+		"discard",
+		"reindex",
+		"rollback",
+		"vacuum",
+	};
+	for (i = 0; non_tx_stmts[i]; i++)
+		if (pg_strncasecmp(stmt, non_tx_stmts[i], strlen(non_tx_stmts[i])) == 0)
+					else if ((ProxyingGUCs || MultitenantProxy)
+							 && chan->buf[msg_start] == 'Q' && !chan->in_transaction)
+						if (ProxyingGUCs
+							&& pg_strncasecmp(stmt, "set", 3) == 0
+						else if (chan->gucs && is_transactional_statement(stmt))

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 
 
index 3bf96de..6036703 100644
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 10;
@@ -148,3 +154,6 @@ int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
 
 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
+bool        ProxyingGUCs = false;
+bool        MultitenantProxy = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index fc46360..06cbae3 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -457,6 +457,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
@@ -1286,6 +1294,36 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
+		{"restart_pooler_on_reload", PGC_SIGHUP, CONN_POOLING,
+		 gettext_noop("Restart session pool workers on pg_reload_conf()."),
+		 NULL,
+		},
+		&RestartPoolerOnReload,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"proxying_gucs", PGC_USERSET, CONN_POOLING,
+		 gettext_noop("Support setting parameters in connection pooler sessions."),
+		 NULL,
+		},
+		&ProxyingGUCs,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
+		{"multitenant_proxy", PGC_USERSET, CONN_POOLING,
+		 gettext_noop("One pool worker can serve clients with different roles"),
+		 NULL,
+		},
+		&MultitenantProxy,
+		false,
+		NULL, NULL, NULL
+	},
+
+	{
 		{"log_duration", PGC_SUSET, LOGGING_WHAT,
 			gettext_noop("Logs the duration of each completed SQL statement."),
 			NULL
@@ -2138,6 +2176,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2185,6 +2270,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4550,6 +4645,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8146,6 +8251,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS
 
index 61a24c2..8a31f4e 100644
@@ -159,6 +159,22 @@ extern PGDLLIMPORT int data_directory_mode;
+extern PGDLLIMPORT bool MultitenantProxy;

 

 

 

 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 9 Sep 2019 18:12:28 +0300

> will be very pleased to receive it.

I was able to reproduce the crash.
Patch is attached. Also I added proxyign of RESET command.
Unfortunately it is still not enough to pass regression tests with 
"proxying_gucs=on".
Mostly because error messages doesn't match after prepending "set local" 
commands.

 

 

 

 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..3bf2f2f
@@ -0,0 +1,1359 @@
+	int      magic;
+#define ACTIVE_CHANNEL_MAGIC    0xDEFA1234U
+#define REMOVED_CHANNEL_MAGIC   0xDEADDEEDU
+		"create tablespace",
+		"create database",
+							&& ((pg_strncasecmp(stmt, "set", 3) == 0
+								|| pg_strncasecmp(stmt, "reset", 5) == 0))
+							if (pg_strncasecmp(stmt, "reset", 5) == 0)
+								char* semi = strchr(stmt+5, ';');
+								if (semi)
+									*semi = '\0';
+								chan->gucs = psprintf("%sset local%s=default;",
+													  chan->prev_gucs, stmt+5);
+								char* param = stmt + 3;
+								if (pg_strncasecmp(param, " session", 8) == 0)
+									param += 8;
+								chan->gucs = psprintf("%sset local%s%c", chan->prev_gucs, param,
+	chan->magic = ACTIVE_CHANNEL_MAGIC;
+		chan->magic = REMOVED_CHANNEL_MAGIC;
+		chan->magic = REMOVED_CHANNEL_MAGIC;
+	chan->magic = REMOVED_CHANNEL_MAGIC;
+			 * epoll may return event for already closed session if
+			 * socket is still openned. From epoll documentation: Q6
+			 * Will closing a file descriptor cause it to be removed
+			 * from all epoll sets automatically?
+			 * A6  Yes, but be aware of the following point.  A file
+			 * descriptor is a reference to an open file description
+			 * (see open(2)).  Whenever a descriptor is duplicated via
+			 * dup(2), dup2(2), fcntl(2) F_DUPFD, or fork(2), a new
+			 * file descriptor referring to the same open file
+			 * description is created.  An open file  description
+			 * continues  to exist until  all  file  descriptors
+			 * referring to it have been closed.  A file descriptor is
+			 * removed from an epoll set only after all the file
+			 * descriptors referring to the underlying open file
+			 * description  have been closed  (or  before  if  the
+			 * descriptor is explicitly removed using epoll_ctl(2)
+			 * EPOLL_CTL_DEL).  This means that even after a file
+			 * descriptor that is part of an epoll set has been
+			 * closed, events may be reported  for that  file
+			 * descriptor  if  other  file descriptors referring to
+			 * the same underlying file description remain open.
+			 * Using this check for valid magic field we try to ignore
+			 * such events.
+			else if (chan->magic == ACTIVE_CHANNEL_MAGIC)
+					if (chan->magic == ACTIVE_CHANNEL_MAGIC && (chan->peer == NULL || chan->peer->tx_size == 0)) /* nothing to write */
+					if (chan->magic == ACTIVE_CHANNEL_MAGIC && chan->tx_size != 0) /* pending write: read is not prohibited */

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 	{
 
 	{
 
 	{
 
+	{
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Wed, 11 Sep 2019 17:56:13 +0300

On 09.09.2019 18:12, Konstantin Knizhnik wrote:
> Mostly because error messages doesn't match after prepending "set 
> local" commands.
>
>

I have implemented passing startup options to pooler backend.
Now "make installcheck" is passed without  manual setting 
datestyle/timezone/intervalstyle in postgresql.conf.

 

 

 

 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..eb8dcad
@@ -0,0 +1,1482 @@
+#define NULLSTR(s) ((s) ? (s) : "?")
+ * Control structure for connection proxies (several proxy workers can be launched and each has its own proxy instance).
+	List*    startup_gucs;        /* List of startup options specified in startup packet */
+	char*    cmdline_options;     /* Command line options passed to backend */
+static size_t
+string_length(char const* str)
+	size_t spaces = 0;
+	char const* p = str;
+	if (p == NULL)
+	while (*p != '\0')
+		spaces += (*p++ == ' ');
+	return (p - str) + spaces;
+static size_t
+string_list_length(List* list)
+	ListCell *cell;
+	size_t length = 0;
+	foreach (cell, list)
+		length += strlen((char*)lfirst(cell));
+	return length;
+static List*
+string_list_copy(List* orig)
+	List* copy = list_copy(orig);
+	ListCell *cell;
+	foreach (cell, copy)
+		lfirst(cell) = pstrdup((char*)lfirst(cell));
+	return copy;
+string_list_equal(List* a, List* b)
+	const ListCell *ca, *cb;
+	if (list_length(a) != list_length(b))
+	forboth(ca, a, cb, b)
+		if (strcmp(lfirst(ca), lfirst(cb)) != 0)
+static char*
+string_append(char* dst, char const* src)
+	while (*src)
+		if (*src == ' ')
+			*dst++ = '\\';
+		*dst++ = *src++;
+	return dst;
+string_equal(char const* a, char const* b)
+	return a == b ? true : a == NULL || b == NULL ? false : strcmp(a, b) == 0;
+		chan->pool->startup_gucs = NULL;
+		chan->pool->cmdline_options = NULL;
+		/* Assume that all clients are using the same set of GUCs.
+		 * Use then for launching pooler worker backends and report error
+		 * if GUCs in startup packets are different.
+		if (chan->pool->n_launched_backends == 0)
+			list_free(chan->pool->startup_gucs);
+			if (chan->pool->cmdline_options)
+				pfree(chan->pool->cmdline_options);
+			chan->pool->startup_gucs = string_list_copy(chan->client_port->guc_options);
+			if (chan->client_port->cmdline_options)
+				chan->pool->cmdline_options = pstrdup(chan->client_port->cmdline_options);
+			if (!string_list_equal(chan->pool->startup_gucs, chan->client_port->guc_options) ||
+				!string_equal(chan->pool->cmdline_options, chan->client_port->cmdline_options))
+				elog(LOG, "Ignoring GUCs of client %s",
+					 NULLSTR(chan->client_port->application_name));
+	char* options = (char*)palloc(string_length(pool->cmdline_options) + string_list_length(pool->startup_gucs) + list_length(pool->startup_gucs)/2*5 + 1);
+	char const* keywords[] = {"port","dbname","user","sslmode","application_name","options",NULL};
+	char const* values[] = {postmaster_port,pool->key.database,pool->key.username,"disable","pool_worker",options,NULL};
+	ListCell *gucopts;
+	char* dst = options;
+	gucopts = list_head(pool->startup_gucs);
+	if (pool->cmdline_options)
+		dst += sprintf(dst, "%s", pool->cmdline_options);
+		gucopts = lnext(pool->startup_gucs, gucopts);
+		gucopts = lnext(pool->startup_gucs, gucopts);
+		if (strcmp(name, "application_name") != 0)
+			dst += sprintf(dst, " -c %s=", name);
+			dst = string_append(dst, value);
+	*dst = '\0';
+	pfree(options);

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 	{
 
 	{
 
 	{
 
+	{
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Alvaro Herrera <[email-masked]>
Date: Wed, 25 Sep 2019 17:14:04 -0300

Travis complains that the SGML docs are broken.  Please fix.

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 26 Sep 2019 10:17:09 +0300

> Travis complains that the SGML docs are broken.  Please fix.

Sorry.
Patch with fixed SGML formating error is attached.

 

 

index 0000000..c63ba26
+    will be create only for each database and current user is explicitly specified for each transaction/standalone statement using <literal>set command</literal> clause.

 
 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..b8723d8
@@ -0,0 +1,1485 @@
+	int		 n_dedicated_backends;/* Number of dedicated (tainted) backends */
+		chan->pool->n_dedicated_backends += 1;
+		if (chan->pool->n_launched_backends == chan->pool->n_dedicated_backends)
+				elog(LOG, "Ignoring startup GUCs of client %s",
+		chan->pool->n_dedicated_backends -= chan->backend_is_tainted;

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 	{
 
 	{
 
 	{
 
+	{
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Konstantin Knizhnik <[email-masked]>
Date: Fri, 27 Sep 2019 15:07:18 +0300

New version of builtin connection pooler fixing handling messages of 
extended protocol.

 

 

 

 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..6d9dfdc
@@ -0,0 +1,1506 @@
+			ELOG(LOG, "Send command %c from client %d to backend %d (%p:ready=%d)", peer->buf[peer->tx_pos], peer->client_port->sock, chan->backend_pid, chan, chan->backend_is_ready);
+			ELOG(LOG, "Send reply %c to client %d from backend %d (%p:ready=%d)", peer->buf[peer->tx_pos], chan->client_port->sock, peer->backend_pid, peer, peer->backend_is_ready);
+			ELOG(LOG, "Receive reply %c %d bytes from backend %d (%p:ready=%d) to client %d", chan->buf[0] ? chan->buf[0] : '?', (int)rc + chan->rx_pos, chan->backend_pid, chan, chan->backend_is_ready, chan->peer ? chan->peer->client_port->sock : -1);
+			ELOG(LOG, "Receive command %c %d bytes from client %d to backend %d (%p:ready=%d)", chan->buf[0] ? chan->buf[0] : '?', (int)rc + chan->rx_pos, chan->client_port->sock, chan->peer ? chan->peer->backend_pid : -1, chan->peer, chan->peer ? chan->peer->backend_is_ready : -1);
+							if (chan->rx_pos + gucs_len + 1 > chan->buf_size)
+								chan->buf_size = chan->rx_pos + gucs_len + 1;
+								Assert(chan->buf[chan->rx_pos-1] == '\0');
+								if (chan->buf[chan->rx_pos-2] != ';')
+									chan->buf[chan->rx_pos-1] = ';';
+									chan->rx_pos += 1;
+									msg_len += 1;
+		elog(LOG, "Message size %d", msg_start);
+						elog(LOG, "Send handshake response to the client");
+						elog(LOG, "Handshake response will be sent to the client later when backed is assigned");
+					chan->tx_size = msg_start; /* query will be send later once backend is assigned */
+					elog(LOG, "Query will be sent to this client later when backed is assigned");

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

 	{
 
 	{
 
 	{
 
+	{
 
+	if (!stmt->is_local)

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: "[email-masked]" <[email-masked]>
Date: Tue, 12 Nov 2019 07:50:44 +0000

Hi.

>From: Konstantin Knizhnik [mailto:[email-masked]]
>
>New version of builtin connection pooler fixing handling messages of extended
>protocol.
>
Here are things I've noticed.

1. Is adding guc to postgresql.conf.sample useful for users?

2. When proxy_port is a bit large (perhaps more than 2^15), connection failed
though regular "port" is fine with number more than 2^15.

$ bin/psql -p  32768
2019-11-12 16:11:25.460 JST [5617] LOG:  Message size 84
2019-11-12 16:11:25.461 JST [5617] WARNING:  could not setup local connect to server
2019-11-12 16:11:25.461 JST [5617] DETAIL:  invalid port number: "-22768"
2019-11-12 16:11:25.461 JST [5617] LOG:  Handshake response will be sent to the client later when backed is assigned
psql: error: could not connect to server: invalid port number: "-22768"

3. When porxy_port is 6543 and connection_proxies is 2, running "make installcheck" twice without restarting server failed.
This is because of remaining backend.

============== dropping database "regression"         ==============
ERROR:  database "regression" is being accessed by other users
DETAIL:  There is 1 other session using the database.
command failed: "/usr/local/pgsql-connection-proxy-performance/bin/psql" -X -c "DROP DATABASE IF EXISTS \"regression\"" "postgres"

4. When running "make installcheck-world" with various connection-proxies, it results in a different number of errors.
With connection_proxies = 2, the test never ends. With connection_proxies = 20, 23 tests failed.
More connection_proxies, the number of failed tests decreased.

Regards,
Takeshi Ideriha

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 12 Nov 2019 18:59:20 +0300

Hi

> 1. Is adding guc to postgresql.conf.sample useful for users?
Good catch: I will add it.

> psql: error: could not connect to server: invalid port number: "-22768"
Hmmm, ProxyPortNumber is used exactly in the same way as PostPortNumber.
I was able to connect to the specified port:

knizhnik@knizhnik:~/dtm-data$ psql postgres -p 42768
psql (13devel)
Type "help" for help.

postgres=# \q
knizhnik@knizhnik:~/dtm-data$ psql postgres -h 127.0.0.1 -p 42768
psql (13devel)
Type "help" for help.

postgres=# \q

> command failed: "/usr/local/pgsql-connection-proxy-performance/bin/psql" -X -c "DROP DATABASE IF EXISTS \"regression\"" "postgres"
Yes, this is known limitation.
Frankly speaking I do not consider it as a problem: it is not possible 
to drop database while there are active sessions accessing it.
And definitely proxy has such sessions. You can specify 
idle_pool_worker_timeout to shutdown pooler workers after  some idle time.
In this case, if you make large enough pause between test iterations, 
then workers will be terminated and it will be possible to drop database.

> More connection_proxies, the number of failed tests decreased.
Please notice, that each proxy maintains its own connection pool.
Default number of pooled backends is 10 (session_pool_size).
If you specify too large number of proxies then number of spawned backends =
  session_pool_size * connection_proxies can be too large (for the 
specified number of max_connections).

Please notice the difference between number of proxies and number of 
pooler backends.
Usually one proxy process is enough to serve all workers. Only in case 
of MPP systems with large number of cores
and especially with SSL connections, proxy can become a bottleneck. In 
this case you can configure several proxies.
But having more than 1-4 proxies seems to be bad idea.

But in case of check-world the problem is not related with number of 
proxies.
It takes place even with connection_proxies = 1
There was one bug with handling clients terminated inside transaction.
It is fixed in the attached patch.
But there is still problem with passing isolation tests under connection 
proxy: them are using pg_isolation_test_session_is_blocked
function which checks if backends with specified PIDs are blocked. But 
as far as in case of using connection proxy session is no more bounded 
to the particular backend, this check may not work as expected and test 
is blocked. I do not know how it can be fixed and not sure if it has to 
be fixed at all.

 

 

 

 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

 /*
+ * StartProxyWorker

 

index 0000000..618a891
@@ -0,0 +1,1514 @@
+	if (is_new || (!chan->backend_is_tainted && !chan->backend_proc->is_tainted)) /* If backend is not storing some session context */
+						elog(DEBUG1, "Receive 'X' to backend %d", backend != NULL ? backend->backend_pid : 0);
+						if (backend != NULL && !backend->backend_is_ready && !backend->backend_is_tainted)
+							/* If client send abort inside transaction, then mark backend as tainted */
+							backend->backend_is_tainted = true;
+						if (backend == NULL || !backend->backend_is_tainted)
+		elog(DEBUG1, "Message size %d", msg_start);
+						elog(DEBUG1, "Send handshake response to the client");
+						elog(DEBUG1, "Handshake response will be sent to the client later when backed is assigned");
+					elog(DEBUG1, "Query will be sent to this client later when backed is assigned");

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 
index fc46360..7e91742 100644

 	{
 
 	{
+			gettext_noop("Maximal number of client sessions which can be handled by one connection proxy."
 
 	{
+		{"proxy_port", PGC_POSTMASTER, CONN_POOLING,
 
+	{
+		{"session_schedule", PGC_POSTMASTER, CONN_POOLING,
 
+	if (!stmt->is_local)
+		MyProc->is_tainted = true;
+
 	switch (stmt->kind)
 	{
 		case VAR_SET_VALUE:
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index cfad86c..73f0902 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -744,6 +744,19 @@
 #include_if_exists = ''			# include file only if it exists
 #include = ''				# include file
 
+#------------------------------------------------------------------------------
+# BUILTIN CONNECTION PROXY
+#------------------------------------------------------------------------------
+
+#proxy_port = 6543              # TCP port for the connection pooler
+#connection_proxies = 0         # number of connection proxies. Setting it to non-zero value enables builtin connection proxy.
+#idle_pool_worker_timeout = 0   # maximum allowed duration of any idling connection pool worker.
+#session_pool_size = 10         # number of backends serving client sessions.
+#restart_pooler_on_reload = off # restart session pool workers on pg_reload_conf().
+#proxying_gucs = off            # support setting parameters in connection pooler sessions.
+#multitenant_proxy = off        # one pool worker can serve clients with different roles (otherwise separate pool is created for each database/role pair
+#max_sessions = 1000            # maximum number of client sessions which can be handled by one connection proxy.
+#session_schedule = 'round-robin' # session schedule policy for connection pool.
 
 #------------------------------------------------------------------------------
 # CUSTOMIZED OPTIONS

-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: "[email-masked]" <[email-masked]>
Date: Thu, 14 Nov 2019 01:17:19 +0000

Hi

>> 2. When proxy_port is a bit large (perhaps more than 2^15), connection
>> failed though regular "port" is fine with number more than 2^15.
>>
>> $ bin/psql -p  32768
>> 2019-11-12 16:11:25.461 JST [5617] LOG:  Handshake response will be
>> sent to the client later when backed is assigned
>knizhnik@knizhnik:~/dtm-data$ psql postgres -p 42768 psql (13devel) Type "help" for
>help.
>
>postgres=# \q
>knizhnik@knizhnik:~/dtm-data$ psql postgres -h 127.0.0.1 -p 42768 psql (13devel)
>Type "help" for help.
>
>postgres=# \q

For now I replay for the above. Oh sorry, I was wrong about the condition.
The error occurred under following condition.
- port = 32768
- proxy_port = 6543
- $ psql postgres -p 6543

$ bin/pg_ctl start -D data
waiting for server to start....
 LOG:  starting PostgreSQL 13devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28), 64-bit
 LOG:  listening on IPv6 address "::1", port 6543
 LOG:  listening on IPv4 address "127.0.0.1", port 6543
 LOG:  listening on IPv6 address "::1", port 32768
 LOG:  listening on IPv4 address "127.0.0.1", port 32768
 LOG:  listening on Unix socket "/tmp/.s.PGSQL.6543"
 LOG:  listening on Unix socket "/tmp/.s.PGSQL.32768"
 LOG:  Start proxy process 25374
 LOG:  Start proxy process 25375
 LOG:  database system was shut down at 2019-11-12 16:49:20 JST
 LOG:  database system is ready to accept connections

server started
[postgres@vm-7kfq-coreban connection-pooling]$ psql -p 6543
LOG:  Message size 84
WARNING:  could not setup local connect to server
DETAIL:  invalid port number: "-32768"
LOG:  Handshake response will be sent to the client later when backed is assigned
psql: error: could not connect to server: invalid port number: "-32768"

By the way, the patch has some small conflicts against master.

Regards,
Takeshi Ideriha

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 14 Nov 2019 10:06:23 +0300

Thank you very much for reporting the problem.
It was caused by using pg_itoa for string representation of port (I 
could not imagine that unlike standard itoa it accepts int16 parameter 
instead of int).
Attached please find rebased patch with this bug fixed.

 

 
 
diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index f837703..7433e6f 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -732,6 +732,169 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>

index e59cba7..1e5aa4f 100644
 
index 7e0a041..1fbfe6b 100644
 
index a13322b..c5a1abe 100644
 
+	/*
+	 * TODO:

 
index 45aae59..968f70f 100644
 
index cd517e8..c0615fd 100644

+	if (FeBeWaitSet)
 
+

diff --git a/src/backend/port/Makefile b/src/backend/port/Makefile
index 2d00b4f..8c763c7 100644
--- a/src/backend/port/Makefile
+++ b/src/backend/port/Makefile
@@ -25,7 +25,8 @@ OBJS = \
 	$(TAS) \
 	atomics.o \
 	pg_sema.o \
-	pg_shmem.o
+	pg_shmem.o \
+	send_sock.o
 
index 03e3d36..0726adb 100644
@@ -23,6 +23,7 @@ OBJS = \
 	postmaster.o \
 	startup.o \
 	syslogger.o \
-	walwriter.o
+	walwriter.o \
+	proxy.o
 
index 9ff2832..edfe12f 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();
 
@@ -1123,6 +1187,11 @@ PostmasterMain(int argc, char *argv[])

@@ -1146,32 +1215,36 @@ PostmasterMain(int argc, char *argv[])
 
@@ -1240,29 +1313,32 @@ PostmasterMain(int argc, char *argv[])

@@ -1272,6 +1348,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
@@ -1397,6 +1487,8 @@ PostmasterMain(int argc, char *argv[])

 	/*
@@ -1634,6 +1726,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
@@ -1724,8 +1867,18 @@ ServerLoop(void)
@@ -1922,8 +2075,6 @@ ProcessStartupPacket(Port *port, bool secure_done)
 
 	pq_startmsgread();
 
@@ -1990,6 +2141,18 @@ ProcessStartupPacket(Port *port, bool secure_done)
 	}
 	pq_endmsgread();
 
@@ -2090,7 +2253,7 @@ retry1:
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2781,6 +2944,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
@@ -2858,6 +3023,9 @@ pmdie(SIGNAL_ARGS)
 
@@ -4108,6 +4276,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4117,8 +4286,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4222,6 +4391,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4918,6 +5089,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -5058,6 +5230,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5601,6 +5786,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
@@ -6205,6 +6458,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6436,6 +6693,9 @@ restore_backend_variables(BackendParameters *param, Port *port)
 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);

index 0000000..0368c71
+	pg_ltoa(PostPortNumber, postmaster_port);
index 4829953..bb6df49 100644
 #include "replication/origin.h"
@@ -150,6 +151,7 @@ CreateSharedMemoryAndSemaphores(void)
 
@@ -255,6 +257,7 @@ CreateSharedMemoryAndSemaphores(void)
 
 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
 /*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);
 
index 9089733..deba84d 100644

index fff0628..b080193 100644
@@ -396,6 +396,7 @@ InitProcess(void)
index d7a72c0..34a4c75 100644
@@ -4245,6 +4245,8 @@ PostgresMain(int argc, char *argv[],

 
 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
+bool        ProxyingGUCs = false;
+bool        MultitenantProxy = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 4b3769b..e03d5a0 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -459,6 +459,14 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 	{NULL, 0, false}
 };
 
@@ -1291,6 +1299,36 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
@@ -2143,6 +2181,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2190,6 +2275,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4577,6 +4672,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8170,6 +8275,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
+		MyProc->is_tainted = true;
+
 	switch (stmt->kind)
 	{
 		case VAR_SET_VALUE:
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index be02a76..ba3300d 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -753,6 +753,19 @@
 #include_if_exists = '...'		# include file only if it exists
 #include = '...'			# include file

index 58ea5b9..9e9c35d 100644
@@ -10731,4 +10731,11 @@

-#ifndef ENABLE_GSS
 
index bc6e03f..92f6f76 100644
 
index 10dcb5f..fd33239 100644

index c459a24..2a541e6 100644
@@ -436,6 +436,7 @@ extern int	pgkill(int pid, int sig);
 
@@ -446,6 +447,7 @@ int			pgwin32_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *except

 

 
 
 typedef struct WaitEvent

 
index 281e1db..76d2b8a 100644
 
index 64468ab..5ae5137 100644
 
-#ifndef ENABLE_GSS
 
index 81089d6..fed76be 100644
@@ -18,6 +18,7 @@ override CPPFLAGS += -DWIN32_STACK_RLIMIT=$(WIN32_STACK_RLIMIT)
index 8a7d6ff..c191fa9 100644
@@ -16,6 +16,7 @@ DLSUFFIX = .dll

 check-tests: all tablespace-setup | temp-install
 	$(pg_regress_check) $(REGRESS_OPTS) $(MAXCONNOPT) $(TESTS) $(EXTRA_TESTS)
diff --git a/src/test/regress/conn_proxy.conf b/src/test/regress/conn_proxy.conf
new file mode 100644
index 0000000..ebaa257
--- /dev/null
+++ b/src/test/regress/conn_proxy.conf
@@ -0,0 +1,3 @@
+connection_proxies = 1
+port = 5432
+log_statement=all
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index 9a0963a..3e5d0e6 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -160,6 +160,7 @@ sub mkvcbuild
 
@@ -273,6 +274,12 @@ sub mkvcbuild
 
+	my $libpqconn =

---

From: David Steele <[email-masked]>
Date: Tue, 24 Mar 2020 09:26:43 -0400

Hi Konstantin,

> Attached please find rebased patch with this bug fixed.

This patch no longer applies: http://cfbot.cputube.org/patch_27_2067.log

CF entry has been updated to Waiting on Author.

Regards,
-- 
-David
[email-masked]

---

From: Konstantin Knizhnik <[email-masked]>
Date: Tue, 24 Mar 2020 19:24:15 +0300

Hi David,

diff --git a/contrib/spi/refint.c b/contrib/spi/refint.c
index 6fbfef2..27aa6cb 100644
--- a/contrib/spi/refint.c
+++ b/contrib/spi/refint.c
@@ -11,6 +11,7 @@
 
@@ -94,6 +95,8 @@ check_primary_key(PG_FUNCTION_ARGS)
 
@@ -286,6 +289,8 @@ check_foreign_key(PG_FUNCTION_ARGS)

index 355b408..23210ba 100644

index 40be506..9bd5dad 100644
@@ -58,6 +59,8 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
 
index 284a5bf..a37654f 100644
@@ -441,6 +442,7 @@ StorePreparedStatement(const char *stmt_name,
 
index 6aab73b..a80c85a 100644
 
+	/*
+	 * TODO:

 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 8e35c5b..b178c34 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -615,6 +615,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index 7717bb2..3ec8849 100644
@@ -193,15 +193,13 @@ pq_init(void)
 
@@ -218,6 +216,11 @@ pq_init(void)
 
+	if (FeBeWaitSet)
@@ -225,6 +228,7 @@ pq_init(void)
 
+
 /* --------------------------------
  *		socket_comm_reset - reset libpq during error recovery
  *
@@ -327,7 +331,7 @@ socket_close(int code, Datum arg)
 int
 StreamServerPort(int family, const char *hostName, unsigned short portNumber,
 				 const char *unixSocketDir,
-				 pgsocket ListenSocket[], int MaxListen)
+				 pgsocket ListenSocket[], int ListenPort[], int MaxListen)
 {
 	pgsocket	fd;
 	int			err;
@@ -591,6 +595,7 @@ StreamServerPort(int family, const char *hostName, unsigned short portNumber,
 							familyDesc, addrDesc, (int) portNumber)));

 
index 0000000..0a90a50
@@ -0,0 +1,158 @@
+	char		c_buffer[CMSG_SPACE(sizeof(sock))];
index 4843507..937d4a4 100644
index bfdf6a8..11dd9c8 100644
@@ -24,6 +24,7 @@ OBJS = \
 	postmaster.o \
 	startup.o \
 	syslogger.o \
-	walwriter.o
+	walwriter.o \
+	proxy.o
 
index 2b9ab32..8345a28 100644

 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2794,6 +2957,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
@@ -2871,6 +3036,9 @@ pmdie(SIGNAL_ARGS)
 
@@ -4121,6 +4289,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4130,8 +4299,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4235,6 +4404,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4936,6 +5107,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -5076,6 +5248,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5619,6 +5804,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
@@ -6223,6 +6476,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6455,6 +6712,9 @@ restore_backend_variables(BackendParameters *param, Port *port)

 	 * We need to restore fd.c's counts of externally-opened FDs; to avoid
 	 * confusion, be sure to do this after restoring max_safe_fds.  (Note:
index 0000000..dc21479
+	init_ps_display("connection proxy");
index 427b0d5..5259c24 100644

 	/*
index e2f4b11..9e0b0f6 100644
@@ -78,11 +78,29 @@

 	/*
 	 * Array, of nevents_space length, storing the definition of events this
@@ -90,6 +108,8 @@ struct WaitEventSet
 	 */
 	WaitEvent  *events;
 
+	int        *permutation;    /* indexes of used events (see comment above) */
+
 	/*
 	 * If WL_LATCH_SET is specified in any wait event, latch is a pointer to
 	 * said latch, and latch_pos the offset in the ->events array. This is
@@ -150,9 +170,9 @@ static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action
 #elif defined(WAIT_USE_KQUEUE)
 static void WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events);
 #elif defined(WAIT_USE_POLL)
-static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event, bool remove);
 #elif defined(WAIT_USE_WIN32)
-static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event);
+static void WaitEventAdjustWin32(WaitEventSet *set, WaitEvent *event, bool remove);
 #endif
 
@@ -574,6 +594,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 
@@ -594,23 +615,23 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 
 #elif defined(WAIT_USE_KQUEUE)
 	set->kqueue_ret_events = (struct kevent *) data;
-	data += MAXALIGN(sizeof(struct kevent) * nevents);
 
 	set->latch = NULL;
 
 #if defined(WAIT_USE_EPOLL)
 	if (!AcquireExternalFD())
@@ -702,12 +723,11 @@ FreeWaitEventSet(WaitEventSet *set)
 	close(set->kqueue_fd);
 	ReleaseExternalFD();
 #elif defined(WAIT_USE_WIN32)
-	WaitEvent  *cur_event;
+	int i;
 
@@ -720,7 +740,7 @@ FreeWaitEventSet(WaitEventSet *set)
@@ -761,9 +781,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -790,8 +812,20 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
@@ -820,15 +854,41 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 #elif defined(WAIT_USE_KQUEUE)
 	WaitEventAdjustKqueue(set, event, 0);
 
 	return event->pos;
 }
 
 /*
@@ -842,13 +902,19 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 	int			old_events;
 #endif

 	event = &set->events[pos];
 #if defined(WAIT_USE_KQUEUE)
 	old_events = event->events;
 #endif
 
+#if defined(WAIT_USE_EPOLL)
+	/* ModifyWaitEvent is used to emulate epoll EPOLLET (edge-triggered) flag */
+	if (events & WL_SOCKET_EDGE)
+		return;
+#endif
+
 	/*
 	 * If neither the event mask nor the associated latch changes, return
 	 * early. That's an important optimization for some sockets, where
@@ -884,9 +950,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 #elif defined(WAIT_USE_KQUEUE)
 	WaitEventAdjustKqueue(set, event, old_events);
 #elif defined(WAIT_USE_POLL)
-	WaitEventAdjustPoll(set, event);
+	WaitEventAdjustPoll(set, event, false);
 #elif defined(WAIT_USE_WIN32)
-	WaitEventAdjustWin32(set, event);
+	WaitEventAdjustWin32(set, event, false);
 #endif
 }
 
@@ -924,6 +990,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -932,11 +1000,10 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
 }
@@ -944,11 +1011,16 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;
 
 	/* prepare pollfd entry once */
@@ -1111,9 +1183,21 @@ WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -1551,11 +1635,12 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 {
 	int			returned_events = 0;
 	int			rc;
-	WaitEvent  *cur_event;
-	struct pollfd *cur_pollfd;
+	int			i;
+	struct pollfd *cur_pollfd = set->pollfds;
+	WaitEvent* cur_event;
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)
@@ -1578,15 +1663,13 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 		return -1;
 	}

@@ -1677,17 +1760,25 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,

@@ -1753,7 +1844,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
@@ -1794,7 +1885,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
 		Assert(cur_event->fd);
 
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 3013ef6..67e03b9 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -801,7 +801,10 @@ LockAcquireExtended(const LOCKTAG *locktag,

index 9938cdd..64bba49 100644
index 00c77b6..225ad64 100644
@@ -4263,6 +4263,8 @@ PostgresMain(int argc, char *argv[],
index ecb1bf9..b007c13 100644
 
index eb19644..6c0cc24 100644

 double		vacuum_cleanup_index_scale_factor;
+bool        RestartPoolerOnReload = false;
+bool        ProxyingGUCs = false;
+bool        MultitenantProxy = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index af876d1..6e0112e 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -489,6 +489,13 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 StaticAssertDecl(lengthof(ssl_protocol_versions_info) == (PG_TLS1_3_VERSION + 2),
 				 "array length mismatch");
 
+static const struct config_enum_entry session_schedule_options[] = {
+	{"round-robin", SESSION_SCHED_ROUND_ROBIN, false},
+	{"random", SESSION_SCHED_RANDOM, false},
+	{"load-balancing", SESSION_SCHED_LOAD_BALANCING, false},
+	{NULL, 0, false}
+};
+
 static struct config_enum_entry shared_memory_options[] = {
 #ifndef WIN32
 	{"sysv", SHMEM_TYPE_SYSV, false},
@@ -685,6 +692,8 @@ const char *const config_group_names[] =
 	gettext_noop("Connections and Authentication / Authentication"),
 	/* CONN_AUTH_SSL */
 	gettext_noop("Connections and Authentication / SSL"),
+	/* CONN_POOLING */
+	gettext_noop("Connections and Authentication / Builtin connection pool"),
 	/* RESOURCES */
 	gettext_noop("Resource Usage"),
 	/* RESOURCES_MEM */
@@ -1373,6 +1382,36 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
@@ -2243,6 +2282,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2290,6 +2376,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4708,6 +4804,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8281,6 +8387,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
index aa44f0c..4aaaff9 100644
@@ -757,6 +757,19 @@

index 87d25d4..74fc5d0 100644
@@ -10819,4 +10819,11 @@
 
index 82e57af..014a302 100644
 
-#ifndef ENABLE_GSS
 
index 4d3a0be..98dff24 100644
-extern int	StreamServerPort(int family, const char *hostName,
-							 unsigned short portNumber, const char *unixSocketDir,
+extern int StreamServerPort(int family, const char *hostName,
+							unsigned short portNumber, const char *unixSocketDir,
index 14fa127..3c25266 100644
 
index 29f3e39..535b88c 100644

index 8b6576b..1e0fec7 100644

 
index babc87d..680ddf6 100644

 
index 46ae56c..a8f2d31 100644

 typedef struct WaitEvent

 
index d217801..1856547 100644
 
index 454c2df..88dbea5 100644
index 72931e6..6a22a21 100644
 
-#ifndef ENABLE_GSS
 
index e72cb2d..183c8de 100644
index 1a31640..2caf6bb 100644

 check-tests: all tablespace-setup | temp-install
 	$(pg_regress_check) $(REGRESS_OPTS) $(MAXCONNOPT) $(TESTS) $(EXTRA_TESTS)
diff --git a/src/test/regress/conn_proxy.conf b/src/test/regress/conn_proxy.conf
new file mode 100644
index 0000000..ebaa257
--- /dev/null
+++ b/src/test/regress/conn_proxy.conf
@@ -0,0 +1,3 @@
+connection_proxies = 1
+port = 5432
+log_statement=all
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index 636428b..0b5f7d1 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -163,6 +163,7 @@ sub mkvcbuild
 
@@ -274,6 +275,12 @@ sub mkvcbuild
 
+	my $libpqconn =
index 672bb2d..f60d4ba 100755

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 1 Jul 2020 11:30:41 +0200

> On 24 Mar 2020, at 17:24, Konstantin Knizhnik <[email-masked]> wrote:

> Rebased version of the patch is attached.

And this patch also fails to apply now, can you please submit a new version?
Marking the entry as Waiting on Author in the meantime.

cheers ./daniel

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 2 Jul 2020 14:33:11 +0300

diff --git a/contrib/spi/refint.c b/contrib/spi/refint.c
index 6fbfef2b12..27aa6cba8e 100644
--- a/contrib/spi/refint.c
+++ b/contrib/spi/refint.c
@@ -11,6 +11,7 @@

 
 
index b81aab239f..aa435d4066 100644
 
index 0000000000..c63ba2626e
index 64b5da0070..c48f585491 100644
 
index c41ce9499b..a8b0c40c6f 100644
@@ -165,6 +165,7 @@ break is not needed in a wider output rendering.
index e4b7483e32..3a24fed96e 100644
 
index 80d6df8ac1..3bd13e3240 100644
 
index 6aab73bfd4..a80c85ac2b 100644
 
+	/*
+	 * TODO:

 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index f79044f39f..84bfd26804 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -617,6 +617,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index 7717bb2719..3ec8849a84 100644

+	if (FeBeWaitSet)
 
+

index 2d00b4f05a..8c763c719d 100644
 
index 0000000000..0a90a50fd4
index 6fbd1ed6fb..b59cc26e16 100644
index bfdf6a833d..11dd9c8733 100644
 
index 0000000000..d950a8c281
index b4d475bb0b..0925b31052 100644

 
 /*
  * Set by the -o option
 
 static int	ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done);
 
 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
@@ -1926,8 +2079,6 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 
 	pq_startmsgread();
 
@@ -1994,6 +2145,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 	}
 	pq_endmsgread();
 
+	return ParseStartupPacket(port, TopMemoryContext, buf, len, ssl_done, gss_done);
+}
+
+int
+ParseStartupPacket(Port *port, MemoryContext memctx, void* buf, int len, bool ssl_done, bool gss_done)
+{
+	ProtocolVersion proto;
+	MemoryContext oldcontext;
+
+	am_walsender = false;
+	am_db_walsender = false;
+
 	/*
 	 * The first field is either a protocol version number or a special
 	 * request code.
@@ -2103,7 +2266,7 @@ retry1:
 	 * not worry about leaking this storage on failure, since we aren't in the
 	 * postmaster process anymore.
 	 */
-	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
+	oldcontext = MemoryContextSwitchTo(memctx);
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2807,6 +2970,8 @@ pmdie(SIGNAL_ARGS)
 				if (WalWriterPID != 0)
 					signal_child(WalWriterPID, SIGTERM);
 
@@ -2884,6 +3049,9 @@ pmdie(SIGNAL_ARGS)
 
@@ -4134,6 +4302,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4143,8 +4312,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4248,6 +4417,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4944,6 +5115,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -5084,6 +5256,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5626,6 +5811,74 @@ StartAutovacuumWorker(void)
 	}
 }
 
+/*
+ * StartProxyWorker
@@ -6231,6 +6484,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6463,6 +6720,9 @@ restore_backend_variables(BackendParameters *param, Port *port)

index 0000000000..dc214790c6
index 427b0d59cd..5259c243bc 100644

 	/*
index 91fa4b619b..c6f2d85879 100644

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

@@ -820,14 +854,40 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
+/*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);
 
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 95989ce79b..a7289026b6 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -813,7 +813,10 @@ LockAcquireExtended(const LOCKTAG *locktag,

index e57fcd2538..f4cff52588 100644
 	MyProc->delayChkpt = false;
index c9424f167c..c046525beb 100644
@@ -4283,6 +4283,8 @@ PostgresMain(int argc, char *argv[],
index e992d1bbfc..c640ffacab 100644
 
index eb19644419..6c0cc24625 100644

index 75fc6f11d6..0246bc89fd 100644
@@ -481,6 +481,13 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 
@@ -678,6 +685,8 @@ const char *const config_group_names[] =
@@ -1364,6 +1373,36 @@ static struct config_bool ConfigureNamesBool[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -2225,6 +2264,53 @@ static struct config_int ConfigureNamesInt[] =
 
+	{
@@ -2272,6 +2358,16 @@ static struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -4755,6 +4851,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8328,6 +8434,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
index 3a25287a39..d3149f2734 100644
@@ -770,6 +770,19 @@

 #------------------------------------------------------------------------------
 # CUSTOMIZED OPTIONS
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 38295aca48..b7f1b1371f 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -10948,4 +10948,11 @@
   proname => 'is_normalized', prorettype => 'bool', proargtypes => 'text text',
   prosrc => 'unicode_is_normalized' },
 
index 179ebaa104..6a8195dc53 100644
 
-#ifndef ENABLE_GSS
 
index b1152475ac..4e0f22300b 100644
index 18bc8a7b90..6ef450be0e 100644
 
index 271ff0d00b..9ba7f7faf9 100644

index 8b6576b23d..1e0fec75be 100644

 
index babc87dfc9..edf587104f 100644

 
+extern int  ParseStartupPacket(struct Port* port, MemoryContext memctx, void* pkg_body, int pkg_size, bool ssl_done, bool gss_done);
index 0000000000..254d0f099e
index 46ae56cae3..a8f2d3194b 100644

 typedef struct WaitEvent

 
index b20e2ad4f6..530bf8d96c 100644
@@ -210,6 +210,8 @@ struct PGPROC
 
index 454c2df487..88dbea510d 100644
index 1de91ae295..aec3306aec 100644
 
-#ifndef ENABLE_GSS
 
index 81089d6257..fed76be9e0 100644
index e72cb2db0e..183c8de2ce 100644
index c830627b00..7f14dcd51c 100644

index 20da7985c1..33a3e6b037 100644
@@ -162,6 +162,7 @@ sub mkvcbuild

+	my $libpqconn =
index 672bb2d650..f60d4ba985 100755

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 2 Jul 2020 16:44:07 +0200

> On 2 Jul 2020, at 13:33, Konstantin Knizhnik <[email-masked]> wrote:

Both Travis and Appveyor fails to compile this version:

proxy.c: In function ‘client_connect’:
proxy.c:302:6: error: too few arguments to function ‘ParseStartupPacket’
  if (ParseStartupPacket(chan->client_port, chan->proxy->parse_ctx, startup_packet+4, startup_packet_size-4, false) != STATUS_OK) /* skip packet size */
      ^
In file included from proxy.c:8:0:
../../../src/include/postmaster/postmaster.h:71:12: note: declared here
 extern int  ParseStartupPacket(struct Port* port, MemoryContext memctx, void* pkg_body, int pkg_size, bool ssl_done, bool gss_done);
            ^
<builtin>: recipe for target 'proxy.o' failed
make[3]: *** [proxy.o] Error 1

cheers ./daniel

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 2 Jul 2020 18:38:02 +0300

> make[3]: *** [proxy.o] Error 1

Sorry, correct patch is attached.

 

 

 
 
+	/*
+	 * TODO:

 

 
+	if (FeBeWaitSet)
 
+

 

 
 
 /*
  * Set by the -o option

 /*
 
+static void
 
 	InitProcessGlobals();

 

 

 
 	/*
 
+/**
 
 	pq_startmsgread();

 

 
 /*
 
 	return STATUS_OK;
 }

+/*
+ * StartProxyWorker

 

index 0000000000..9df2fc4a0b
+	if (ParseStartupPacket(chan->client_port, chan->proxy->parse_ctx, startup_packet+4, startup_packet_size-4, false, false) != STATUS_OK) /* skip packet size */

 	/*

 	/*

 

 	set->latch = NULL;

 
 	/* not enough space */

 
 	return event->pos;
 }
 
+/*

 

 	/*

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;

 
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)

 

 
 		Assert(cur_event->fd);

 

 

+	{
 
+	{
 
+	{
 
+	{
 
+	if (!stmt->is_local)

 
 
-#ifndef ENABLE_GSS

 

 

 

 
 typedef struct WaitEvent

 

-#ifndef ENABLE_GSS

 

+	my $libpqconn =

---

From: Jaime Casanova <[email-masked]>
Date: Sat, 4 Jul 2020 23:17:56 -0500

>          MyProc->is_tainted = true;

You should also allow cursors without the WITH HOLD option or there is
something i'm missing?

a few questions about tainted backends:
- why the use of check_primary_key() and check_foreign_key() in
contrib/spi/refint.c make the backend tainted?
- the comment in src/backend/commands/sequence.c needs some fixes, it
seems just quickly typed

some usability problem:
- i compiled this on a debian machine with "--enable-debug
--enable-cassert --with-pgport=54313", so nothing fancy
- then make, make install, and initdb: so far so good

configuration:
listen_addresses = '*'
connection_proxies = 20

and i got this:

"""
jcasanov@DangerBox:/opt/var/pgdg/14dev$ /opt/var/pgdg/14dev/bin/psql
-h 127.0.0.1 -p 6543 postgres
psql: error: could not connect to server: no se pudo conectar con el
servidor: No existe el fichero o el directorio
¿Está el servidor en ejecución localmente y aceptando
conexiones en el socket de dominio Unix «/var/run/postgresql/.s.PGSQL.54313»?
"""

but connect at the postgres port works well
"""
jcasanov@DangerBox:/opt/var/pgdg/14dev$ /opt/var/pgdg/14dev/bin/psql
-h 127.0.0.1 -p 54313 postgres
psql (14devel)
Type "help" for help.

postgres=# \q
jcasanov@DangerBox:/opt/var/pgdg/14dev$ /opt/var/pgdg/14dev/bin/psql
-p 54313 postgres
psql (14devel)
Type "help" for help.

postgres=#
"""

PS: unix_socket_directories is setted at /tmp and because i'm not
doing this with postgres user i can use /var/run/postgresql

---

From: Konstantin Knizhnik <[email-masked]>
Date: Sun, 5 Jul 2020 16:46:09 +0300

Thank your for your help.

> You should also allow cursors without the WITH HOLD option or there is 

Yes, good point.
> contrib/spi/refint.c make the backend tainted?

I think this is because without it contrib test is not passed with 
connection pooler.
This extension uses static variables which are assumed to be session 
specific  but in case f connection pooler are shared by all backends.

> - the comment in src/backend/commands/sequence.c needs some fixes, it

Sorry, done.

> doing this with postgres user i can use /var/run/postgresql
Looks like for some reasons your Postgres was not configured to accept 
TCP connection.
It accepts only local connections through Unix sockets.
But pooler is not listening unix sockets because there is absolutely no 
sense in pooling local connections.

I have done the same steps as you and have no problem to access pooler:

knizhnik@xps:~/postgresql.vanilla$ psql postgres -h 127.0.0.1 -p 6543
psql (14devel)
Type "help" for help.

postgres=# \q

Please notice that if I specify some unexisted port, then I get error 
message which is different with yours:

knizhnik@xps:~/postgresql.vanilla$ psql postgres -h 127.0.0.1 -p 65433
psql: error: could not connect to server: could not connect to server: 
Connection refused
     Is the server running on host "127.0.0.1" and accepting
     TCP/IP connections on port 65433?

So Postgres is not mentioning unix socket path in this case. It makes me 
think that your server is not accepting TCP connections at all (despite to

listen_addresses = '*'

)

---

From: Michael Paquier <[email-masked]>
Date: Thu, 17 Sep 2020 14:07:11 +0900

> Sorry, correct patch is attached.

This needs again a rebase, and has been waiting on author for 6 weeks
now, so I am switching it to RwF.
--
Michael

---

From: Konstantin Knizhnik <[email-masked]>
Date: Thu, 17 Sep 2020 11:40:59 +0300

> now, so I am switching it to RwF.

Attached is rebased version of the patch.

I wonder what is the correct policy of handling patch status?
This patch was marked as WfA 2020-07-01 because it was not applied any more.
2020-07-02 I have sent rebased version of the patch.
Since this time there was not unanswered questions.
So I actually didn't consider that some extra activity from my side is need.
I have not noticed that patch is not applied any more.
And now it is marked as returned with feedback.

So my questions are:
1. Should I myself change status from WfA to some other?
2. Is there some way to receive notifications that patch is not applied 
any more?

I can resubmit this patch to the next commitfest if it is still 
interesting for community.

 

 
index 2c75876..657216e 100644
 
index 828396d..fb95e61 100644
 
index c41ce94..a8b0c40 100644
index e4b7483..158fb4d 100644
@@ -58,6 +59,9 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
 
+	if (cstmt->options & CURSOR_OPT_HOLD)
index 4b18be5..1ad98fd 100644
 
index 6aab73b..64bf4d1 100644
 
+	/*
+	 * TODO:
+	 * Using currval() may cause incorrect behavior with connection pooler.
+	 * Unfortunately marking backend as tainted in currval() is too late.
+	 * This is why it is done in nextval(), although it is not strictly required, because
+	 * nextval() may be not followed by currval().
+	 * But currval() may be not preceded by nextval().
+	 * To make regression tests passed, backend is also marker as tainted when it creates
+	 * sequence. Certainly it is just temporary workaround, because sequence may be created
+	 * in one backend and accessed in another.
+	 */
+	MyProc->is_tainted = true; /* in case of using currval() */
+
 	return address;
 }

 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index eab570a..3685270 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -619,6 +619,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index ac986c0..b817c7c 100644

+	if (FeBeWaitSet)
 
+

 
index 6fbd1ed..b59cc26 100644
 
index 959e3b8..d84c749 100644
@@ -115,6 +115,7 @@
 #include "postmaster/interrupt.h"
@@ -199,6 +200,9 @@ BackgroundWorker *MyBgworkerEntry = NULL;

@@ -219,6 +223,7 @@ int			ReservedBackends;
 /* The socket(s) we're listening to. */
 #define MAXLISTEN	64
 static pgsocket ListenSocket[MAXLISTEN];
+static int      ListenPort[MAXLISTEN];
 
 /*
  * Set by the -o option
@@ -249,6 +254,18 @@ bool		enable_bonjour = false;
 char	   *bonjour_name;
 bool		restart_after_crash = true;
 
@@ -419,7 +436,6 @@ static void BackendInitialize(Port *port);
@@ -441,6 +457,7 @@ static pid_t StartChildProcess(AuxProcType type);
 
 /*
  * Archiver is allowed to start up at the current postmaster state?
@@ -493,6 +510,8 @@ typedef struct
 {
 	Port		port;
 	InheritableSocket portsocket;
+	InheritableSocket proxySocket;
+	int         proxyId;
 	char		DataDir[MAXPGPATH];
 	pgsocket	ListenSocket[MAXLISTEN];
 	int32		MyCancelKey;
@@ -576,6 +595,48 @@ int			postmaster_alive_fds[2] = {-1, -1};
 HANDLE		PostmasterHandle;
 #endif
 
+static void
@@ -588,6 +649,9 @@ PostmasterMain(int argc, char *argv[])
 
 	InitProcessGlobals();
 
@@ -1138,6 +1202,11 @@ PostmasterMain(int argc, char *argv[])

@@ -1161,32 +1230,36 @@ PostmasterMain(int argc, char *argv[])
 
@@ -1255,29 +1328,32 @@ PostmasterMain(int argc, char *argv[])

@@ -1287,6 +1363,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
@@ -1412,6 +1502,8 @@ PostmasterMain(int argc, char *argv[])

 	/*
@@ -1649,6 +1741,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
@@ -1739,8 +1882,18 @@ ServerLoop(void)
@@ -1943,8 +2096,6 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 
 	pq_startmsgread();
 
@@ -2011,6 +2162,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 	}
 	pq_endmsgread();
 
@@ -2120,7 +2283,7 @@ retry1:
 
 	if (PG_PROTOCOL_MAJOR(proto) >= 3)
 	{
@@ -2827,6 +2990,7 @@ pmdie(SIGNAL_ARGS)
 			else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
 			{
 				/* There should be no clients, so proceed to stop children */
+				StopConnectionProxies(SIGTERM);
 				pmState = PM_STOP_BACKENDS;
 			}
 
@@ -2869,6 +3033,7 @@ pmdie(SIGNAL_ARGS)
 				/* Report that we're about to zap live client sessions */
 				ereport(LOG,
 						(errmsg("aborting any active transactions")));
+				StopConnectionProxies(SIGTERM);
 				pmState = PM_STOP_BACKENDS;
 			}
 
@@ -4144,6 +4309,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4153,8 +4319,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4258,6 +4424,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4971,6 +5139,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -5098,6 +5267,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5652,6 +5834,74 @@ StartAutovacuumWorker(void)
 }
 
 /*
+ * StartProxyWorker
@@ -6255,6 +6505,10 @@ save_backend_variables(BackendParameters *param, Port *port,

 
@@ -6487,6 +6741,9 @@ restore_backend_variables(BackendParameters *param, Port *port)

index 0000000..9df2fc4
index 96c2aaa..b06a1d7 100644
@@ -152,6 +153,7 @@ CreateSharedMemoryAndSemaphores(void)
 
@@ -259,6 +261,7 @@ CreateSharedMemoryAndSemaphores(void)
 
 	/*
index 4153cc8..a3824e1 100644
@@ -79,11 +79,29 @@

 	/*
 	 * Array, of nevents_space length, storing the definition of events this
@@ -91,6 +109,8 @@ struct WaitEventSet
 	 */
 	WaitEvent  *events;
 
@@ -157,9 +177,9 @@ static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action
 
@@ -622,6 +642,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 
@@ -642,23 +663,23 @@ CreateWaitEventSet(MemoryContext context, int nevents)

 	set->latch = NULL;
 
 #if defined(WAIT_USE_EPOLL)
 	if (!AcquireExternalFD())
@@ -750,12 +771,11 @@ FreeWaitEventSet(WaitEventSet *set)
 	close(set->kqueue_fd);
 	ReleaseExternalFD();
 #elif defined(WAIT_USE_WIN32)
-	WaitEvent  *cur_event;
+	int i;
 
@@ -768,7 +788,7 @@ FreeWaitEventSet(WaitEventSet *set)
@@ -809,9 +829,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -838,8 +860,20 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
@@ -868,15 +902,41 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
 /*
  * with the WaitEvent.  The latch may be changed to NULL to disable the latch
  * temporarily, and then set back to a latch later.
@@ -891,13 +951,19 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 	int			old_events;
 #endif

 
@@ -932,9 +998,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
@@ -972,6 +1038,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -980,11 +1048,10 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
 }
@@ -992,11 +1059,16 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;
 
 	/* prepare pollfd entry once */
@@ -1159,9 +1231,21 @@ WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -1599,11 +1683,12 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 {
 	int			returned_events = 0;
 	int			rc;
-	WaitEvent  *cur_event;
-	struct pollfd *cur_pollfd;
+	int			i;
+	struct pollfd *cur_pollfd = set->pollfds;
+	WaitEvent* cur_event;
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)
@@ -1626,15 +1711,13 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 		return -1;
 	}

@@ -1725,17 +1808,25 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,

@@ -1801,7 +1892,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
@@ -1842,7 +1933,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
 		Assert(cur_event->fd);
 
index d86566f..129853f 100644

index 88566bd..79dbd82 100644
@@ -392,6 +392,7 @@ InitProcess(void)
 	MyProc->vacuumFlags = 0;
index 411cfad..524df57 100644
@@ -4277,6 +4277,8 @@ PostgresMain(int argc, char *argv[],
index f592292..b72a487 100644
 
index 6ab8216..e07332e 100644
@@ -131,9 +131,15 @@ int			max_parallel_maintenance_workers = 2;
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 10;
@@ -149,3 +155,6 @@ int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
 
index 596bcb7..feb8669 100644
@@ -485,6 +485,13 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 
@@ -683,6 +690,8 @@ const char *const config_group_names[] =
@@ -1360,6 +1369,36 @@ static struct config_bool ConfigureNamesBool[] =
 	},
 
 	{
@@ -2221,6 +2260,53 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -2279,6 +2365,16 @@ static struct config_int ConfigureNamesInt[] =
 	},
 
 	{
@@ -4784,6 +4880,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -8357,6 +8463,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 
+	if (!stmt->is_local)
index 9cb571f..9d73306 100644
@@ -775,6 +775,19 @@

index 687509b..0bbc44f 100644
@@ -10972,4 +10972,11 @@
 
index 0a23281..5aa5abb 100644
 
-#ifndef ENABLE_GSS
 
index b115247..4e0f223 100644
index 72e3352..4e1d72c 100644
 
index 84bf2c3..f9f64d2 100644

 

index babc87d..edf5871 100644

 
index 7c74202..d53ccec 100644

 typedef struct WaitEvent

@@ -178,6 +183,8 @@ extern int	WaitLatchOrSocket(Latch *latch, int wakeEvents,
 							  pgsocket sock, long timeout, uint32 wait_event_info);
 extern void InitializeLatchWaitSet(void);
 
index 9c9a50a..ffa16bd 100644
@@ -239,6 +239,8 @@ struct PGPROC
 
index 04431d0..19c2595 100644
index 1de91ae..aec3306 100644
 
-#ifndef ENABLE_GSS
 
index c830627..7f14dcd 100644

index 89e1b39..3e3135b 100644

+	my $libpqconn =

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 17 Sep 2020 10:47:42 +0200

> On 17 Sep 2020, at 10:40, Konstantin Knizhnik <[email-masked]> wrote:

> 1. Should I myself change status from WfA to some other?

Yes, when you've addressed any issues raised and posted a new version it's very
helpful to the CFM and the community if you update the status.

> 2. Is there some way to receive notifications that patch is not applied any more?

Not at the moment, but periodically checking the CFBot page for your patches is
a good habit:

	http://cfbot.cputube.org/konstantin-knizhnik.html

cheers ./daniel

---

From: Konstantin Knizhnik <[email-masked]>
Date: Sun, 21 Mar 2021 21:32:28 +0300

People asked me to resubmit built-in connection pooler patch to commitfest.
Rebased version of connection pooler is attached.

 

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index ee4925d6d9..4c862bbae9 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -734,6 +734,169 @@ include_dir 'conf.d'
       </listitem>
      </varlistentry>
 
index db1d369743..7911e0029b 100644
 
index 730d5fdc34..13db3ff32e 100644
@@ -166,6 +166,7 @@ break is not needed in a wider output rendering.
index 79e274a476..da1c8b548c 100644
index 6f2397bd36..f80577e3d8 100644
@@ -59,6 +60,9 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
 
index f767751c71..f73d7563b6 100644
@@ -439,6 +440,7 @@ StorePreparedStatement(const char *stmt_name,
 
index 0415df9ccb..f0ee21e8f4 100644
 
+	/*
+	 * TODO:

 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9b2800bf5e..3186615b73 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -623,6 +623,10 @@ DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId,
 				(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
 				 errmsg("ON COMMIT can only be used on temporary tables")));
 
index 4c7b1e7bfd..51b82aa96c 100644
@@ -177,14 +177,12 @@ pq_init(void)

@@ -201,6 +199,11 @@ pq_init(void)
 
+	if (FeBeWaitSet)
+		FreeWaitEventSet(FeBeWaitSet);
+	else
+		on_proc_exit(socket_close, 0);
+
 	FeBeWaitSet = CreateWaitEventSet(TopMemoryContext, 3);
 	socket_pos = AddWaitEventToSet(FeBeWaitSet, WL_SOCKET_WRITEABLE,
 								   MyProcPort->sock, NULL, NULL);
@@ -217,6 +220,7 @@ pq_init(void)
 	Assert(latch_pos == FeBeWaitSetLatchPos);
 }
 
+
 /* --------------------------------
  *		socket_comm_reset - reset libpq during error recovery
  *
@@ -314,7 +318,7 @@ socket_close(int code, Datum arg)
 int
 StreamServerPort(int family, const char *hostName, unsigned short portNumber,
 				 const char *unixSocketDir,
-				 pgsocket ListenSocket[], int MaxListen)
+				 pgsocket ListenSocket[], int ListenPort[], int MaxListen)
 {
 	pgsocket	fd;
 	int			err;
@@ -580,6 +584,7 @@ StreamServerPort(int family, const char *hostName, unsigned short portNumber,
 							familyDesc, addrDesc, (int) portNumber)));

 
index a8012c2798..bc43300f93 100644
@@ -698,3 +698,65 @@ pgwin32_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, c
 
index ef0be4ca38..a39a85a739 100644
@@ -198,6 +199,9 @@ BackgroundWorker *MyBgworkerEntry = NULL;

@@ -218,6 +222,7 @@ int			ReservedBackends;
 /* The socket(s) we're listening to. */
 #define MAXLISTEN	64
 static pgsocket ListenSocket[MAXLISTEN];
+static int      ListenPort[MAXLISTEN];
 
 /*
  * These globals control the behavior of the postmaster in case some
@@ -244,6 +249,18 @@ char	   *bonjour_name;
 bool		restart_after_crash = true;
 bool		remove_temp_files_after_crash = true;
 
@@ -414,7 +431,6 @@ static void BackendInitialize(Port *port);
@@ -436,6 +452,7 @@ static pid_t StartChildProcess(AuxProcType type);
 
 /*
  * Archiver is allowed to start up at the current postmaster state?
@@ -489,6 +506,8 @@ typedef struct
 {
 	Port		port;
 	InheritableSocket portsocket;
+	InheritableSocket proxySocket;
+	int         proxyId;
 	char		DataDir[MAXPGPATH];
 	pgsocket	ListenSocket[MAXLISTEN];
 	int32		MyCancelKey;
@@ -572,6 +591,48 @@ int			postmaster_alive_fds[2] = {-1, -1};
 HANDLE		PostmasterHandle;
 #endif
 
+static void
@@ -584,6 +645,9 @@ PostmasterMain(int argc, char *argv[])
 
 	InitProcessGlobals();
 
@@ -1131,6 +1195,11 @@ PostmasterMain(int argc, char *argv[])

@@ -1154,32 +1223,36 @@ PostmasterMain(int argc, char *argv[])
 
@@ -1249,29 +1322,32 @@ PostmasterMain(int argc, char *argv[])

@@ -1281,6 +1357,20 @@ PostmasterMain(int argc, char *argv[])
 	}
 #endif
 
@@ -1406,6 +1496,8 @@ PostmasterMain(int argc, char *argv[])

 	/*
@@ -1644,6 +1736,57 @@ DetermineSleepTime(struct timeval *timeout)
 	}
 }
 
+/**
@@ -1734,8 +1877,18 @@ ServerLoop(void)
@@ -1938,8 +2091,6 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 	char	   *buf;
 
 	pq_startmsgread();
 
@@ -2003,6 +2154,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
 	}
 	pq_endmsgread();
 
@@ -2113,7 +2276,7 @@ retry1:
 
 	/* Handle protocol version 3 startup packet */
 	{
@@ -2129,7 +2292,7 @@ retry1:
 
 		while (offset < len)
 		{
-			char	   *nameptr = buf + offset;
+			char	   *nameptr = (char*)buf + offset;
 			int32		valoffset;
 			char	   *valptr;
 
@@ -2138,7 +2301,7 @@ retry1:
 			valoffset = offset + strlen(nameptr) + 1;
 			if (valoffset >= len)
 				break;			/* missing value, will complain below */
-			valptr = buf + valoffset;
+			valptr = (char*)buf + valoffset;
 
 			if (strcmp(nameptr, "database") == 0)
 				port->database_name = pstrdup(valptr);
@@ -2781,6 +2944,7 @@ pmdie(SIGNAL_ARGS)
 			else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
 			{
 				/* There should be no clients, so proceed to stop children */
+				StopConnectionProxies(SIGTERM);
 				pmState = PM_STOP_BACKENDS;
 			}
 
@@ -2823,6 +2987,7 @@ pmdie(SIGNAL_ARGS)
 
@@ -4111,6 +4276,7 @@ TerminateChildren(int signal)
 		signal_child(PgArchPID, signal);
 	if (PgStatPID != 0)
 		signal_child(PgStatPID, signal);
+	StopConnectionProxies(signal);
 }
 
 /*
@@ -4120,8 +4286,8 @@ TerminateChildren(int signal)
  *
  * Note: if you change this code, also consider StartAutovacuumWorker.
  */
-static int
-BackendStartup(Port *port)
+int
+BackendStartup(Port *port, int* backend_pid)
 {
 	Backend    *bn;				/* for backend cleanup */
 	pid_t		pid;
@@ -4225,6 +4391,8 @@ BackendStartup(Port *port)
 	if (!bn->dead_end)
 		ShmemBackendArrayAdd(bn);
 #endif
+	if (backend_pid)
+		*backend_pid = pid;
 
 	return STATUS_OK;
 }
@@ -4894,6 +5062,7 @@ SubPostmasterMain(int argc, char *argv[])
 	if (strcmp(argv[1], "--forkbackend") == 0 ||
 		strcmp(argv[1], "--forkavlauncher") == 0 ||
 		strcmp(argv[1], "--forkavworker") == 0 ||
+		strcmp(argv[1], "--forkproxy") == 0 ||
 		strcmp(argv[1], "--forkboot") == 0 ||
 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
 		PGSharedMemoryReAttach();
@@ -5021,6 +5190,19 @@ SubPostmasterMain(int argc, char *argv[])
 
@@ -5564,6 +5746,74 @@ StartAutovacuumWorker(void)
 	}
 }
 
+/*
+ * StartProxyWorker
@@ -6170,6 +6420,10 @@ save_backend_variables(BackendParameters *param, Port *port,
 
 	strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);

@@ -6400,6 +6654,9 @@ restore_backend_variables(BackendParameters *param, Port *port)

index 3e4ec53a97..a05150cbc5 100644
@@ -153,6 +154,7 @@ CreateSharedMemoryAndSemaphores(void)
 
@@ -261,6 +263,7 @@ CreateSharedMemoryAndSemaphores(void)
 	PgArchShmemInit();
 
 	/*
index 43a5fded10..5b0c92bc19 100644
@@ -81,15 +81,30 @@
 
-#ifdef WAIT_USE_EPOLL
+#if defined(WAIT_USE_EPOLL)
 #include <sys/signalfd.h>
+bool WaitEventUseEpoll = true;
+#else
+bool WaitEventUseEpoll = false;
 #endif
 
+/*
 
 	/*
 	 * Array, of nevents_space length, storing the definition of events this
@@ -97,6 +112,8 @@ struct WaitEventSet
 	 */
 	WaitEvent  *events;
 
@@ -174,9 +191,9 @@ static void WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action
 
@@ -695,6 +712,7 @@ CreateWaitEventSet(MemoryContext context, int nevents)
 
@@ -715,23 +733,23 @@ CreateWaitEventSet(MemoryContext context, int nevents)

 	set->latch = NULL;
 
 #if defined(WAIT_USE_EPOLL)
 	if (!AcquireExternalFD())
@@ -804,12 +822,11 @@ FreeWaitEventSet(WaitEventSet *set)
 	close(set->kqueue_fd);
 	ReleaseExternalFD();
 #elif defined(WAIT_USE_WIN32)
-	WaitEvent  *cur_event;
+	int i;
 
@@ -822,7 +839,7 @@ FreeWaitEventSet(WaitEventSet *set)
@@ -863,9 +880,11 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 				  void *user_data)
 {
 	WaitEvent  *event;
+	int free_event;
 
 	/* not enough space */
 
 	if (events == WL_EXIT_ON_PM_DEATH)
 	{
@@ -892,8 +911,20 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 	if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
 		elog(ERROR, "cannot wait on socket event without a socket");
 
@@ -929,14 +960,40 @@ AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch,
 
 	return event->pos;
 }
 
+/*
@@ -952,13 +1009,19 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 	int			old_events;
 #endif

 
@@ -1009,9 +1072,9 @@ ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
@@ -1049,6 +1112,8 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 
 	/*
@@ -1057,11 +1122,10 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)
 	 * requiring that, and actually it makes the code simpler...
 	 */
 	rc = epoll_ctl(set->epoll_fd, action, event->fd, &epoll_ev);
-
 	if (rc < 0)
 		ereport(ERROR,
 				(errcode_for_socket_access(),
-		/* translator: %s is a syscall name, such as "poll()" */
+				 /* translator: %s is a syscall name, such as "poll()" */
 				 errmsg("%s failed: %m",
 						"epoll_ctl()")));
 }
@@ -1069,11 +1133,16 @@ WaitEventAdjustEpoll(WaitEventSet *set, WaitEvent *event, int action)

-	pollfd->revents = 0;
 	pollfd->fd = event->fd;
 
 	/* prepare pollfd entry once */
@@ -1252,9 +1321,21 @@ WaitEventAdjustKqueue(WaitEventSet *set, WaitEvent *event, int old_events)

 	if (event->events == WL_LATCH_SET)
 	{
@@ -1716,11 +1797,12 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 {
 	int			returned_events = 0;
 	int			rc;
-	WaitEvent  *cur_event;
-	struct pollfd *cur_pollfd;
+	int			i;
+	struct pollfd *cur_pollfd = set->pollfds;
+	WaitEvent* cur_event;
 
 	/* Sleep */
 
 	/* Check return code */
 	if (rc < 0)
@@ -1743,15 +1825,13 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 		return -1;
 	}

@@ -1842,17 +1922,25 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,

@@ -1918,7 +2006,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
@@ -1963,7 +2051,7 @@ WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout,
 
 		Assert(cur_event->fd);
 
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 108b4d9023..718c0ae9fd 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -812,7 +812,10 @@ LockAcquireExtended(const LOCKTAG *locktag,

index 897045ee27..eadb87260c 100644
@@ -394,6 +394,7 @@ InitProcess(void)
 	MyProc->statusFlags = 0;
index 2b1b68109f..e0d4bb7800 100644
@@ -4383,6 +4383,8 @@ PostgresMain(int argc, char *argv[],
index 97f0265c12..841e746bb9 100644
 
@@ -675,12 +676,14 @@ pg_isolation_test_session_is_blocked(PG_FUNCTION_ARGS)
  *	field4: 1 if using an int8 key, 2 if using 2 int4 keys
  */
 #define SET_LOCKTAG_INT64(tag, key64) \
+	MyProc->is_tainted = true; \
 	SET_LOCKTAG_ADVISORY(tag, \
 						 MyDatabaseId, \
 						 (uint32) ((key64) >> 32), \
 						 (uint32) (key64), \
 						 1)
 #define SET_LOCKTAG_INT32(tag, key1, key2) \
+	MyProc->is_tainted = true; \
 	SET_LOCKTAG_ADVISORY(tag, MyDatabaseId, key1, key2, 2)
 
 /*
index 73e0a672ae..a35e4a33a8 100644
@@ -132,9 +132,15 @@ int			max_parallel_maintenance_workers = 2;
 
 int			VacuumCostPageHit = 1;	/* GUC parameters for vacuum */
 int			VacuumCostPageMiss = 2;
@@ -148,3 +154,6 @@ int64		VacuumPageDirty = 0;
 
 int			VacuumCostBalance = 0;	/* working state for vacuum */
 bool		VacuumCostActive = false;
+bool        RestartPoolerOnReload = false;
+bool        ProxyingGUCs = false;
+bool        MultitenantProxy = false;
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index 3b36a31a47..106d18ef7e 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -488,6 +488,13 @@ const struct config_enum_entry ssl_protocol_versions_info[] = {
 StaticAssertDecl(lengthof(ssl_protocol_versions_info) == (PG_TLS1_3_VERSION + 2),
 				 "array length mismatch");
 
+static const struct config_enum_entry session_schedule_options[] = {
+	{"round-robin", SESSION_SCHED_ROUND_ROBIN, false},
+	{"random", SESSION_SCHED_RANDOM, false},
+	{"load-balancing", SESSION_SCHED_LOAD_BALANCING, false},
+	{NULL, 0, false}
+};
+
 static struct config_enum_entry recovery_init_sync_method_options[] = {
 	{"fsync", RECOVERY_INIT_SYNC_METHOD_FSYNC, false},
 #ifdef HAVE_SYNCFS
@@ -695,6 +702,8 @@ const char *const config_group_names[] =
 	gettext_noop("Connections and Authentication / Authentication"),
 	/* CONN_AUTH_SSL */
 	gettext_noop("Connections and Authentication / SSL"),
+	/* CONN_POOLING */
+	gettext_noop("Connections and Authentication / Builtin connection pool"),
 	/* RESOURCES */
 	gettext_noop("Resource Usage"),
 	/* RESOURCES_MEM */
@@ -1390,6 +1399,36 @@ static struct config_bool ConfigureNamesBool[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -2270,6 +2309,53 @@ static struct config_int ConfigureNamesInt[] =
 
+	{
@@ -2328,6 +2414,16 @@ static struct config_int ConfigureNamesInt[] =
 		NULL, NULL, NULL
 	},
 
+	{
@@ -4879,6 +4975,16 @@ static struct config_enum ConfigureNamesEnum[] =
 		NULL, NULL, NULL
 	},
 
+	{
+		{"session_schedule", PGC_POSTMASTER, CONN_POOLING,
+			gettext_noop("Session schedule policy for connection pool."),
+			NULL
+		},
+		&SessionSchedule,
+		SESSION_SCHED_ROUND_ROBIN, session_schedule_options,
+		NULL, NULL, NULL
+	},
+
 	{
 		{"recovery_init_sync_method", PGC_POSTMASTER, ERROR_HANDLING_OPTIONS,
 			gettext_noop("Sets the method for synchronizing the data directory before crash recovery."),
@@ -8582,6 +8688,9 @@ ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel)
 				(errcode(ERRCODE_INVALID_TRANSACTION_STATE),
 				 errmsg("cannot set parameters during a parallel operation")));
 
+	if (!stmt->is_local)
index 86425965d0..214232a4b5 100644
@@ -780,6 +780,19 @@

 #------------------------------------------------------------------------------
 # CUSTOMIZED OPTIONS
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index e259531f60..d93549d947 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -8170,7 +8170,7 @@
   proname => 'gist_poly_distance', prorettype => 'float8',
   proargtypes => 'internal polygon int2 oid internal',
   prosrc => 'gist_poly_distance' },
-{ oid => '3435', descr => 'sort support',
+{ oid => '6105', descr => 'sort support',
   proname => 'gist_point_sortsupport', prorettype => 'void',
   proargtypes => 'internal', prosrc => 'gist_point_sortsupport' },
 
@@ -11411,4 +11411,11 @@
 
index 30fb4e613d..a78d31a896 100644
 
-#ifndef ENABLE_GSS
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index b20deeb555..83aae64872 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -56,7 +56,8 @@ extern WaitEventSet *FeBeWaitSet;
 
 extern int	StreamServerPort(int family, const char *hostName,
 							 unsigned short portNumber, const char *unixSocketDir,
index 013850ac28..b858859e4c 100644
@@ -160,6 +160,22 @@ extern PGDLLIMPORT int data_directory_mode;
 
index 227ef4b148..22901d0803 100644

index 05c5a53442..18d93ed275 100644
@@ -464,6 +464,7 @@ extern int	pgkill(int pid, int sig);
 
@@ -474,6 +475,7 @@ int			pgwin32_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *except

index 0efdd7c232..e4f012751c 100644
@@ -47,6 +48,11 @@ extern int	postmaster_alive_fds[2];

 
index 9e94fcaec2..91956bbe93 100644
@@ -134,9 +134,11 @@ typedef struct Latch

 typedef struct WaitEvent
@@ -144,12 +146,15 @@ typedef struct WaitEvent

@@ -180,4 +185,6 @@ extern int	WaitLatchOrSocket(Latch *latch, int wakeEvents,
 							  pgsocket sock, long timeout, uint32 wait_event_info);
 extern void InitializeLatchWaitSet(void);
 
 #endif							/* LATCH_H */
index 2fd1ff09a7..7fc26f0476 100644
@@ -251,6 +251,8 @@ struct PGPROC
 
index b9b5c1adda..631d151032 100644
index 6374ec657a..06622796c3 100644
 
-#ifndef ENABLE_GSS
 
index 95e4bc8228..ca96a92954 100644
@@ -123,6 +123,7 @@ REGRESS_OPTS = --dlpath=. --max-concurrent-tests=20 $(EXTRA_REGRESS_OPTS)
 
 check: all
 
 check-tests: all | temp-install
 	$(pg_regress_check) $(REGRESS_OPTS) $(MAXCONNOPT) $(TESTS) $(EXTRA_TESTS)
diff --git a/src/test/regress/conn_proxy.conf b/src/test/regress/conn_proxy.conf
new file mode 100644
index 0000000000..ebaa257f4b
--- /dev/null
+++ b/src/test/regress/conn_proxy.conf
@@ -0,0 +1,3 @@
+connection_proxies = 1
+port = 5432
+log_statement=all
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index a184404e21..2c8e8e5278 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -168,6 +168,7 @@ sub mkvcbuild
 
@@ -279,6 +280,12 @@ sub mkvcbuild
 
+	my $libpqconn =
index 0cc91e7d6c..6eeb2e7090 100755

---

From: Zhihong Yu <[email-masked]>
Date: Sun, 21 Mar 2021 13:59:09 -0700

Hi,

+          With <literal>load-balancing</literal> policy postmaster choose
proxy with lowest load average.
+          Load average of proxy is estimated by number of clients
connection assigned to this proxy with extra weight for SSL connections.

I think 'load-balanced' may be better than 'load-balancing'.
postmaster choose proxy -> postmaster chooses proxy

+          Load average of proxy is estimated by number of clients
connection assigned to this proxy with extra weight for SSL connections.

I wonder if there would be a mixture of connections with and without SSL.

+         Terminate an idle connection pool worker after the specified
number of milliseconds.

Should the time unit be seconds ? It seems a worker would exist for at
least a second.

It would be better to update the year in the header.

Not sure I understand the above sentence. Did you mean 'them' instead of
'then' ?

Cheers

---

From: Konstantin Knizhnik <[email-masked]>
Date: Mon, 22 Mar 2021 12:05:53 +0300

Hi,
Thank you for review!

> I think 'load-balanced' may be better than 'load-balancing'.

Sorry, I am not a native speaker.
But it seems to me (based on the articles I have read), then 
"load-balancing" is more widely used term:

https://en.wikipedia.org/wiki/Load_balancing_(computing)

Fixed.

> I wonder if there would be a mixture of connections with and without SSL.
Why not? And what is wrong with it?

> Should the time unit be seconds ? It seems a worker would exist for at 
Most of other similar timeouts: statement timeout, session timeout... 
are specified in milliseconds.

Fixed.

> Not sure I understand the above sentence. Did you mean 'them' instead 
> of 'then' ?

Sorry, it is really mistyping.
"them" should be used.
Fixed.

---

From: Antonin Houska <[email-masked]>
Date: Wed, 28 Apr 2021 12:14:56 +0200

> Rebased version of connection pooler is attached.

I've reviewd the patch but haven't read the entire thread thoroughly. I hope
that I don't duplicate many comments posted earlier by others.

(Please note that the patch does not apply to the current master, I had to
reset the head of my repository to the appropriate commit.)

Documentation / user interface
------------------------------

* session_pool_size (config.sgml)

I wonder if

    "The default value is 10, so up to 10 backends will serve each database,"

should rather be

    "The default value is 10, so up to 10 backends will serve each database/user combination."

However, when I read the code, I think that each proxy counts the size of the
pool separately, so the total number of backends used for particular
database/user combination seems to be

    session_pool_size * connection_proxies

Since the feature uses shared memory statistics anyway, shouldn't it only
count the total number of backends per database/user? It would need some
locking, but the actual pools (hash tables) could still be local to the proxy
processes.

* connection_proxies

(I've noticed that Ryan Lambert questioned this variable upthread.)

I think this variable makes the configuration less straightforward from the
user perspective. Cannot the server launch additional proxies dynamically, as
needed, e.g. based on the shared memory statistics that the patch introduces?
I see that postmaster would have to send the sockets in a different way. How
about adding a "proxy launcher" process that would take care of the scheduling
and launching new proxies?

* multitenant_proxy

I thought the purpose of this setting is to reduce the number of backends
needed, but could not find evidence in the code. In particular,
client_attach() always retrieves the backend from the appropriate pool, and
backend_reschedule() does so as well. Thus the role of both client and backend
should always match. What piece of information do I miss?

* typo (2 occurrences in config.sgml)

  "stanalone" -> "standalone"

Design / coding
---------------

* proxy.c:backend_start() does not change the value of the "host" parameter to
  the socket directory, so I assume the proxy connects to the backend via TCP
  protocol. I think the unix socket should be preferred for this connection if
  the platform has it, however:

* is libpq necessary for the proxy to connect to backend at all? Maybe
  postgres.c:ReadCommand() can be adjusted so that the backend can communicate
  with the proxy just via the plain socket.

  I don't like the idea of server components communicating via libpq (do we
  need anything else of the libpq connection than the socket?) as such, but
  especially these includes in proxy.c look weird:

* How does the proxy recognize connections to the walsender? I haven't tested
  that, but it's obvious that these connections should not be proxied.

* ConnectionProxyState is in shared memory, so access to its fields should be
  synchronized.

* StartConnectionProxies() is only called from PostmasterMain(), so I'm not
  sure the proxies get restarted after crash. Perhaps PostmasterStateMachine()
  needs to call it too after calling StartupDataBase().

* Why do you need the Channel.magic integer field? Wouldn't a boolean field
  "active" be sufficient?

  ** In proxy_loop(), I've noticed tests (chan->magic == ACTIVE_CHANNEL_MAGIC)
     tests inside the branch

     else if (chan->magic == ACTIVE_CHANNEL_MAGIC)

     Since neither channel_write() nor channel_read() seem to change the
     value, I think those tests are not necessary.

* Comment lines are often too long.

* pgindent should be applied to the patch at some point.

I can spend more time reviewing the patch during the next CF.

-- 
Antonin Houska
Web: https://www.cybertec-postgresql.com