Skip to content

Commit e5df179

Browse files
authored
Reduce memory and CPU footprint of mirroring (#369)
The experimental mirroring feature used a lot of memory and CPU when put under production traffic. This change attempts to reduce memory and CPU usage. Memory footprint is reduced by making the channel smaller. CPU usage is reduced by avoiding allocations if the channel is full or is closed. We might lose more messages this way if the mirror falls behind but that is more acceptable than crashing the entire process when it goes out-of-memory (OOM)
1 parent 9a668e5 commit e5df179

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/mirrors.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ impl MirroringManager {
119119
let mut exit_senders: Vec<Sender<()>> = vec![];
120120

121121
addresses.iter().for_each(|mirror| {
122-
let (bytes_tx, bytes_rx) = channel::<Bytes>(500);
122+
let (bytes_tx, bytes_rx) = channel::<Bytes>(10);
123123
let (exit_tx, exit_rx) = channel::<()>(1);
124124
let mut addr = mirror.clone();
125125
addr.role = Role::Mirror;
@@ -142,15 +142,25 @@ impl MirroringManager {
142142
}
143143

144144
pub fn send(self: &mut Self, bytes: &BytesMut) {
145-
let cpy = bytes.clone().freeze();
146-
self.byte_senders
147-
.iter_mut()
148-
.for_each(|sender| match sender.try_send(cpy.clone()) {
145+
// We want to avoid performing an allocation if we won't be able to send the message
146+
// There is a possibility of a race here where we check the capacity and then the channel is
147+
// closed or the capacity is reduced to 0, but mirroring is best effort anyway
148+
if self
149+
.byte_senders
150+
.iter()
151+
.all(|sender| sender.capacity() == 0 || sender.is_closed())
152+
{
153+
return;
154+
}
155+
let immutable_bytes = bytes.clone().freeze();
156+
self.byte_senders.iter_mut().for_each(|sender| {
157+
match sender.try_send(immutable_bytes.clone()) {
149158
Ok(_) => {}
150159
Err(err) => {
151160
warn!("Failed to send bytes to a mirror channel {}", err);
152161
}
153-
});
162+
}
163+
});
154164
}
155165

156166
pub fn disconnect(self: &mut Self) {

0 commit comments

Comments
 (0)