Escaping Electron: Architecting an Ultra-Fast WhatsApp Desktop Client in Rust and egui
Explore how pairing an immediate-mode GUI with Rust's async ecosystem unlocks a desktop messaging client that idles under 30MB of RAM. We break down the end-to-end architecture across Noise protocol handshakes, Protobuf deserialization, and lock-free thread synchronization.
The Bloat of Modern Messaging: Deconstructing the Electron Tax
Modern desktop communication tools have normalized an absurd baseline: running multiple full-fledged instances of Google Chrome to display plain text messages. Popular chat applications built on the Electron framework routinely demand between 600MB and 1.2GB of Resident Set Size (RSS) memory at idle. The reasons are systemic to the platform:
- The Multiprocess Model: Electron separates the main Node.js process from Chromium renderers, utility sub-processes, GPU sandboxes, and network services, each allocating baseline heap memory.
- The V8 Garbage Collector: JavaScript memory management leans heavily on generational GC heuristics, deferring memory sweeps and creating bloated allocation floors.
- DOM Virtualization Overhead: Rendering dynamic lists with complex DOM trees creates massive layout recalculation and style resolution trees inside Blink.
For developers and power users monitoring hardware resources, this inefficiency is unnecessary. Projects like ZapFast prove that by replacing Chromium with Rust and an immediate-mode GUI library like egui, we can achieve instant cold-boot startup times (<40ms), smooth 120 FPS scrolling, and an idle memory footprint under 28MB. Below is an architectural breakdown of how to design and build a high-performance native desktop WhatsApp client from scratch.
Immediate-Mode vs. Retained-Mode: Why egui Fits Message Streams
Traditional desktop and web interfaces rely on Retained-Mode GUI (RM-GUI) architectures. In an RM-GUI system (such as the browser DOM, Qt, or GTK), the developer constructs a persistent tree of stateful widgets. When a chat message arrives, the framework mutates an existing node, recalculates bounding boxes, runs dirty-region checks, and invalidates the layout tree.
In contrast, Immediate-Mode GUI (IM-GUI) eliminates persistent UI state trees entirely. The UI is completely redrawn every single frame directly from raw application data. egui executes this pipeline with remarkable efficiency:
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading(&self.active_chat.name);
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.stick_to_bottom(true)
.show_rows(ui, row_height, self.messages.len(), |ui, row_range| {
for idx in row_range {
render_message_bubble(ui, &self.messages[idx]);
}
});
});
}
Why Immediate-Mode Solves Virtualized Scrolling
In chat clients, infinite scrolling over historical logs is notoriously complex in RM-GUI frameworks. egui::ScrollArea::show_rows dynamically calculates the clip viewport geometry based on the parent container's vertical offset. It only runs layout and text tessellation for messages that are currently visible within the target frustum. Off-screen messages incur zero layout cost, zero vertex allocations, and zero GC pressure.
The resulting render output is flattened into a lightweight batch of indexed triangles (egui::ClippedPrimitive) sent directly to the GPU via wgpu or glow. This eliminates the multiple abstraction layers present in Chromium's Compositor Thread and Skia pipelines.
The Protocol Core: Reverse-Engineering Multi-Device WebSockets
WhatsApp’s Multi-Device architecture treats the primary mobile device and registered desktop clients as equal crypto-endpoints connected to the WhatsApp Server (chatd) through a persistent secure WebSocket pipeline. To build a native client, you must implement the WhatsApp wire protocol directly.
1. The Cryptographic Handshake (Noise Protocol Framework)
Before exchanging application payloads, the client authenticates using a custom implementation of the Noise_XX_25519_AESGCM_SHA256 handshake protocol pattern:
- Pattern:
XXallows mutual authentication where both client and server exchange public keys and prove identities without pre-shared knowledge. - Ephemeral Key Exchange: The client generates an ephemeral Curve25519 keypair and sends the public key (
e). - Server Response: The server replies with its ephemeral key (
e) and an encrypted payload containing its static public identity key (s), authenticated viaHMAC-SHA256. - Cipher Initialization: Once the handshake finalizes, both endpoints derive symmetric keys using
HKDF-SHA256to instantiate two AES-256-GCM cipher streams (one for client-to-server transmission, one for server-to-client reception).
pub struct NoiseCipherState {
encrypter: Aes256Gcm,
decrypter: Aes256Gcm,
write_counter: u64,
read_counter: u64,
}
impl NoiseCipherState {
pub fn decrypt_frame(&mut self, payload: &[u8]) -> Result<Vec<u8>, ProtocolError> {
let mut nonce = [0u8; 12];
nonce[4..].copy_from_slice(&self.read_counter.to_be_bytes());
let decrypted = self.decrypter
.decrypt(GenericArray::from_slice(&nonce), payload)
.map_err(|_| ProtocolError::AeadDecryptionFailure)?;
self.read_counter += 1;
Ok(decrypted)
}
}
2. Binary Protobuf Frames
WhatsApp transmits application frames as binary-packed Protocol Buffers wrapped inside an encrypted framing layer. Once a WebSocket frame is decrypted by the NoiseCipherState, it reveals an inner frame consisting of an authentication tag, a binary metric byte, and a serialized WebMessageInfo Protobuf buffer.
By leveraging prost in Rust, incoming binary buffers deserialize directly into stack-allocated structs without temporary JSON or intermediate string conversions, enabling microsecond message parsing.
Concurrency Architecture: Bridging Tokio and the egui Render Thread
A critical challenge in building non-blocking GUI applications in Rust is managing the boundary between an asynchronous network runtime (tokio) and a synchronous, event-driven OS render loop managed by winit and egui.
+-------------------------------------------------------------------------+
| Tokio Async Runtime |
| |
| +--------------------+ Raw Bytes +-----------------------------+ |
| | WebSocket Reactor | -------------> | Noise Decryptor & Protobuf | |
| +--------------------+ +-----------------------------+ |
+-------------------------------------------------------|-----------------+
| Bounded Channel
| (crossbeam / mpsc)
v
+-------------------------------------------------------------------------+
| Main UI Thread (egui) |
| |
| +---------------------+ Frame Tick +----------------------------+ |
| | State Update Engine | <------------- | winit / egui Render Loop | |
| +---------------------+ +----------------------------+ |
+-------------------------------------------------------------------------+
Avoiding Render Stalls with Bounded Lock-Free Channels
If the GUI loop locks a shared Arc<Mutex<ChatState>> to read messages while the network thread holds the lock to append incoming batch payloads, frame drops will occur. To solve this:
- The network thread communicates with the UI thread strictly via message-passing over bounded, lock-free channels (
crossbeam_channel::bounded(1024)). - The main UI thread drains pending events from the channel at the beginning of each frame execution.
- UI operations that mutate state (such as sending a message) dispatch an immutable action enum back down a command channel to the async runtime.
pub enum ClientEvent {
MessageReceived(Box<MessagePayload>),
ReceiptUpdated { id: String, status: DeliveryStatus },
PresenceChanged { jid: Jid, online: bool },
}
pub struct ChatApp {
events_rx: crossbeam_channel::Receiver<ClientEvent>,
cmd_tx: tokio::sync::mpsc::UnboundedSender<ClientCommand>,
chat_db: BTreeMap<Jid, Vec<MessagePayload>>,
}
impl ChatApp {
fn process_incoming_events(&mut self) {
while let Ok(event) = self.events_rx.try_recv() {
match event {
ClientEvent::MessageReceived(msg) => {
self.chat_db.entry(msg.sender.clone()).or_default().push(*msg);
}
ClientEvent::ReceiptUpdated { id, status } => {
self.update_receipt_indicator(&id, status);
}
ClientEvent::PresenceChanged { jid, online } => {
self.update_presence_status(jid, online);
}
}
}
}
}
By ensuring that try_recv() is non-blocking, the UI maintains a responsive 60 or 120 FPS frame rate even during network latency spikes or heavy bulk synchronization.
Performance and Memory Footprint: The Real Numbers
Running native binaries compiled directly for the host operating system's platform APIs yields massive performance gains across all major resource metrics:
| Metric | WhatsApp Desktop (Electron) | Native Rust + egui Client | | :--- | :--- | :--- | | Cold Boot Time | ~2.80 - 4.50 s | 0.038 s (38 ms) | | Idle RAM (RSS) | 580 MB – 850 MB | 24 MB – 28 MB | | Active Scroll RAM | 920 MB – 1.4 GB | 42 MB | | Binary Distributable Size | ~180 MB | ~12 MB (Statically linked) | | Thread Count | 32 - 45 OS Threads | 4 OS Threads (1 UI, 3 Worker) |
Key Strategies for Extreme Resource Optimization
- Zero-Copy Byte Slices: Utilize Rust's slice references (
&[u8]) throughout decryption, Protobuf decoding, and text parsing to avoid unnecessary heap allocations. - Offloading Image Pipeline to Rayon: Thumbnail rendering and avatar decoding occur asynchronously in background worker threads. Once decoded into a raw RGBA buffer, the frame transitions into a GPU-side texture allocation via
egui::Context::load_texturewithout stalling the rendering thread. - Stripped Allocators: Replacing the platform's default memory allocator with
mimallocorjemallocyields a consistent 15% reduction in allocation latency during high-volume chat ingestion.
Conclusion: The Case for Native Systems GUIs
The dominance of Electron was driven by developer convenience: web development skills translated directly to cross-platform desktop shells. However, as modern systems programming languages have matured, that trade-off is no longer mandatory.
By pairing Rust's memory safety and rich asynchronous ecosystem with an immediate-mode rendering engine like egui, software engineers can build maintainable, responsive, and cross-platform desktop clients that treat hardware resources with respect. Native desktop applications aren't dead—they were just waiting for a better toolkit.