@@ -81,7 +81,7 @@ ConnectionPool::~ConnectionPool() {
8181 cv_.notify_all ();
8282 std::unique_lock<std::mutex> lock (mtx_);
8383 while (!available_connections_.empty ()) {
84- close (available_connections_.front ());
84+ close (available_connections_.top ());
8585 available_connections_.pop ();
8686 }
8787}
@@ -96,7 +96,7 @@ bool ConnectionPool::Initialize() {
9696 int fd = CreateConnection ();
9797 if (fd < 0 ) {
9898 while (!available_connections_.empty ()) {
99- close (available_connections_.front ());
99+ close (available_connections_.top ());
100100 available_connections_.pop ();
101101 }
102102 return false ;
@@ -215,8 +215,12 @@ std::optional<ScopedConnection> ConnectionPool::GetConnection(int timeout_ms) {
215215 return std::nullopt ;
216216 }
217217
218- // Pop the oldest connection from the FIFO queue.
219- int fd = available_connections_.front ();
218+ // Pop the most recently used connection from the LIFO stack.
219+ // LIFO (Last-In, First-Out) is preferred for connection pools as it
220+ // increases the likelihood of reusing "hot" connections that still have
221+ // active TCP state (e.g., large congestion windows) and are still cached
222+ // in the kernel/CPU.
223+ int fd = available_connections_.top ();
220224 available_connections_.pop ();
221225
222226 // Verify the connection's health before handing it to the caller.
@@ -227,7 +231,7 @@ std::optional<ScopedConnection> ConnectionPool::GetConnection(int timeout_ms) {
227231 }
228232
229233 // The connection is dead. We close it and attempt to retrieve another
230- // one from the queue .
234+ // one from the stack .
231235 LOG (INFO) << " ConnectionPool::GetConnection: discarded dead connection; "
232236 " retrying with next available connection" ;
233237 close (fd);
@@ -246,7 +250,7 @@ std::optional<ScopedConnection> ConnectionPool::GetConnection(int timeout_ms) {
246250// Returns a connection to the pool, allowing it to be reused.
247251//
248252// If `reuse` is true and the pool is not full, the connection is added back to
249- // the queue of available connections. Otherwise, the connection is closed.
253+ // the stack of available connections. Otherwise, the connection is closed.
250254void ConnectionPool::ReleaseConnection (int sockfd, bool reuse) {
251255 if (sockfd < 0 ) {
252256 LOG (WARNING) << " ConnectionPool::ReleaseConnection: invalid sockfd" ;
@@ -264,6 +268,8 @@ void ConnectionPool::ReleaseConnection(int sockfd, bool reuse) {
264268 if (reuse) {
265269 if (available_connections_.size () < max_size_) {
266270 LOG (INFO) << " ConnectionPool::ReleaseConnection: reuse connection" ;
271+ // We push to the stack to ensure this connection is the first to be
272+ // reused by the next caller (LIFO).
267273 available_connections_.push (sockfd);
268274 cv_.notify_one ();
269275 } else {
0 commit comments