Skip to content

Commit ca6d4b8

Browse files
committed
tokio-postgres: buffer sockets to avoid excessive syscalls
The current implementation forwards all read requests to the operating system through the socket causing excessive system calls. The effect is magnified when the underlying Socket is wrapped around a TLS implementation. This commit changes the underlying socket to be read-buffered by default with a buffer size of 16K, following the implementation of the official client. Signed-off-by: Petros Angelatos <petrosagg@gmail.com>
1 parent 52de269 commit ca6d4b8

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

postgres-native-tls/src/lib.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ use std::future::Future;
5151
use std::io;
5252
use std::pin::Pin;
5353
use std::task::{Context, Poll};
54-
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
54+
use tokio::io::{AsyncRead, AsyncWrite, BufReader, ReadBuf};
5555
use tokio_postgres::tls;
5656
#[cfg(feature = "runtime")]
5757
use tokio_postgres::tls::MakeTlsConnect;
@@ -115,6 +115,7 @@ where
115115
type Future = Pin<Box<dyn Future<Output = Result<TlsStream<S>, native_tls::Error>> + Send>>;
116116

117117
fn connect(self, stream: S) -> Self::Future {
118+
let stream = BufReader::with_capacity(8192, stream);
118119
let future = async move {
119120
let stream = self.connector.connect(&self.domain, stream).await?;
120121

@@ -126,7 +127,7 @@ where
126127
}
127128

128129
/// The stream returned by `TlsConnector`.
129-
pub struct TlsStream<S>(tokio_native_tls::TlsStream<S>);
130+
pub struct TlsStream<S>(tokio_native_tls::TlsStream<BufReader<S>>);
130131

131132
impl<S> AsyncRead for TlsStream<S>
132133
where

postgres-openssl/src/lib.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ use std::pin::Pin;
5757
#[cfg(feature = "runtime")]
5858
use std::sync::Arc;
5959
use std::task::{Context, Poll};
60-
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
60+
use tokio::io::{AsyncRead, AsyncWrite, BufReader, ReadBuf};
6161
use tokio_openssl::SslStream;
6262
use tokio_postgres::tls;
6363
#[cfg(feature = "runtime")]
@@ -140,6 +140,7 @@ where
140140
type Future = Pin<Box<dyn Future<Output = Result<TlsStream<S>, Self::Error>> + Send>>;
141141

142142
fn connect(self, stream: S) -> Self::Future {
143+
let stream = BufReader::with_capacity(8192, stream);
143144
let future = async move {
144145
let ssl = self.ssl.into_ssl(&self.domain)?;
145146
let mut stream = SslStream::new(ssl, stream)?;
@@ -182,7 +183,7 @@ impl Error for ConnectError {
182183
}
183184

184185
/// The stream returned by `TlsConnector`.
185-
pub struct TlsStream<S>(SslStream<S>);
186+
pub struct TlsStream<S>(SslStream<BufReader<S>>);
186187

187188
impl<S> AsyncRead for TlsStream<S>
188189
where

0 commit comments

Comments
 (0)