Skip to main content

Overview

WhatsApp-Rust uses a layered storage architecture with pluggable backends. The PersistenceManager manages all state changes, while the Backend trait defines storage operations for device data, Signal protocol keys, app state sync, and protocol-specific data.

Architecture

PersistenceManager

Location: src/store/persistence_manager.rs

Purpose

Manages all device state changes and persistence operations. Acts as the gatekeeper for state modifications.

Structure

Fields:
  • device: In-memory device state (protected by tokio::sync::RwLock; write-locked only during mutations)
  • device_snapshot: Cached Arc<Device> rebuilt under the write guard on every mutation — read by get_device_snapshot() with no contention against writers
  • backend: Storage backend implementation
  • dirty: Flag indicating unsaved changes
  • save_notify: Notification channel for background saver (uses event_listener::Event for runtime-agnostic operation)

Initialization

Key Methods

get_device_snapshot

Purpose: Read-only access to device state
Usage:

modify_device

Purpose: Modify device state with automatic dirty tracking
Usage:

process_command

Purpose: Apply state changes via DeviceCommand
Usage:

Background Saver

Purpose: Periodically persist dirty state to disk
Behavior:
  • Wakes up when notified or after interval
  • Only saves if dirty flag is set
  • Uses optimistic locking (dirty flag)
Start background saver:

Backend Trait

Location: wacore/src/store/traits.rs

Overview

The Backend trait is automatically implemented for any type that implements all four domain-specific traits:

Domain Traits

SignalStore

Purpose: Signal protocol cryptographic operations
Usage Example:

SignalStoreCache

Location: wacore/src/store/signal_cache.rs (re-exported from src/store/signal_cache.rs) The SignalStoreCache provides an in-memory cache layer for Signal protocol state, matching WhatsApp Web’s SignalStoreCache implementation. All crypto operations read and write through this cache, with database writes deferred to explicit flush() calls. Sessions and sender keys are cached as deserialized objects (SessionRecord and SenderKeyRecord respectively), matching WhatsApp Web’s pattern where the JS object IS the cache. Serialization only happens during flush() — not on every store_session or put_sender_key call. Identity stores use Arc<[u8]> byte caches.
Key features:
  • Session object cache: Sessions are stored as SessionRecord objects, eliminating prost encode/decode from the per-message path. Cold loads deserialize from backend bytes once and cache the object; subsequent reads return the cached object directly
  • Sender key object cache: Sender keys are stored as SenderKeyRecord objects (same pattern as sessions), eliminating serialize/deserialize from the per-message group encryption path. Cold loads deserialize from backend bytes once and cache the object
  • Arc previous sessions: SessionRecord.previous_sessions is wrapped in Arc<Vec<SessionStructure>>, making clone O(1) for the ~40 archived sessions. Only rare paths (archive, promote, take/restore) trigger Arc::make_mut
  • Owned store_session: The store_session method takes SessionRecord by value, enabling zero-cost moves from the protocol layer. The compiler enforces no use-after-store
  • Deferred writes: Changes are accumulated in memory and batch-written on flush(). Sessions and sender keys are serialized only during flush(), not on every store
  • Redundant write elimination: For identities (which rarely change), put_dedup() compares incoming bytes against the cached value and skips if identical
  • Negative caching: Known-absent keys are cached as None to avoid repeated DB lookups
  • Independent locking: Sessions, identities, and sender keys each have their own mutex
  • O(1) key cloning: Keys stored as Arc<str> so cloning a key is a refcount bump instead of a heap allocation. The key_for() method reuses existing Arc<str> keys from the HashMap via get_key_value(), avoiding heap allocation on the hot path
  • Single-allocation keys: Session lock keys use to_protocol_address_string() (format: user[:device]@server.0) which builds the key string in one allocation, avoiding the two-allocation overhead of constructing a ProtocolAddress then calling .to_string(). See Signal Protocol performance for details
Cache operations:
Flush behavior:
  • Acquires all three mutexes to ensure consistency
  • Sessions are serialized to bytes only during flush (not on every put_session)
  • Only clears dirty tracking after ALL writes succeed
  • On failure, dirty state is preserved for retry on next flush

AppSyncStore

Purpose: WhatsApp app state synchronization
AppStateSyncKey Structure:
Collections:
  • critical_block - Blocked contacts, push names
  • regular_high - Mute settings, starred messages, contact info
  • regular_low - Archive settings, pin settings
  • regular - Other chat settings

ProtocolStore

Purpose: WhatsApp Web protocol-specific storage
LidPnMappingEntry:

LidPnCache

Location: src/lid_pn_cache.rs The LidPnCache provides an in-memory cache for LID to phone number mappings, used for Signal address resolution. WhatsApp Web uses LID-based addresses for Signal sessions when available.
Defaults match WAWebLidPnCache:
  • Time-based expiry: none — entries do not idle out
  • Capacity: effectively unbounded (u64::MAX; moka has no unbounded() builder)
A custom CacheEntryConfig can impose a capacity bound if memory pressure requires it. Be aware that capacity-LRU eviction silently downgrades Signal addresses from @lid (or @hosted.lid) back to @c.us, which can cause SessionNotFound decryption failures. Notably, this keeps status@broadcast participants resolving to @lid for the entire session, matching WA Web behavior. Bidirectional lookups:
Since v0.6 get_current_lid (and the SendContextResolver::get_lid_for_phone trait method) returns Option<wacore_binary::CompactString> instead of Option<String>. This avoids a heap allocation on the hot group-send path, since LID identifiers fit inline in a CompactString. Call .as_deref() for &str comparisons, and update any custom SendContextResolver implementation to the new return type.
Timestamp conflict resolution: When multiple LIDs exist for the same phone number, the entry with the most recent created_at timestamp wins for the PN → LID lookup:
Initialization:
Session migration on LID discovery: When a new LID-PN mapping is added to the cache, the client automatically migrates any Signal sessions stored under the PN address to the corresponding LID address. The migration reads and writes through the SignalStoreCache (not the backend directly) to avoid stale reads when the cache has unflushed mutations, then flushes the migrated state to the backend. This prevents SessionNotFound decryption failures when the phone switches from PN to LID addressing. See Signal Protocol — PN→LID session migration for details. Learning sources:
  • usync - User sync responses
  • peer_pn_message / peer_lid_message - Peer messages
  • pairing - Device pairing
  • device_notification - Device notifications
  • blocklist_active / blocklist_inactive - Blocklist operations
DeviceListRecord:
TcTokenEntry:

DeviceStore

Purpose: Device data persistence
Device Structure:
The server_cert_chain field is populated after a successful XX (or XXfallback) handshake and consumed on the next connect to attempt Noise IK. It is cleared via DeviceCommand::ClearServerCertChain if a resumed IK handshake fails crypto-fatally. See Authentication — Noise Protocol Handshake.
The account field uses a custom account_serde module to bridge prost-generated protobuf types (which lack serde::Deserialize) into serde. It encodes AdvSignedDeviceIdentity to protobuf bytes on serialization and decodes them back on deserialization. The #[serde(default)] attribute ensures backward compatibility — old data missing this field deserializes as None.

SqliteStore implementation

Location: storages/sqlite-storage/src/lib.rs
As of v0.5, the whatsapp-rust-sqlite-storage crate bundles SQLite by default via the bundled-sqlite feature. You no longer need SQLite installed as a system dependency. To link against a system SQLite instead, disable the default features on the crate.

Database schema

The device table uses named columns for each field, making the schema self-documenting and reducing the risk of column mix-ups when fields are added:

Multi-Account Support

Each device has unique device_id:
All tables scoped by device_id:

DeviceCommand Pattern

Location: src/store/commands.rs, wacore/src/store/commands.rs

Purpose

Provide type-safe, centralized state mutations.

Command Enum

Command Application

Usage

State management best practices

Read-Only Access

Modifications

Bulk Operations

Critical Errors

Custom backend implementation

Example: PostgreSQL backend

Usage

Migration & Debugging

Database Snapshots

Feature flag: debug-snapshots
Usage:
Output:

Pluggable cache store

Location: src/cache_store.rs, src/cache_config.rs, wacore/src/store/cache.rs

Overview

By default, whatsapp-rust uses in-process moka caches for group metadata, device lists, device registry, and LID-PN mappings. The pluggable cache store adapter lets you replace any of these with an external backend (Redis, Memcached, etc.) by implementing the CacheStore trait.

PortableCache (WASM-compatible alternative)

When the moka-cache feature is disabled, whatsapp-rust automatically switches to PortableCache — a platform-agnostic, runtime-independent cache implementation suitable for WASM and other non-standard runtimes. It mirrors the moka Cache API surface so call-sites can switch transparently. PortableCache supports:
  • Maximum capacity with oldest-inserted eviction
  • Time-to-live (TTL) — entries expire a fixed duration after insertion
  • Time-to-idle (TTI) — entries expire after a fixed duration of no access
  • Single-flight get_with — concurrent initializations for the same key coalesce into a single call, which is critical for caches storing coordination primitives (mutexes, channels)
  • Eager iter() snapshotPortableCache::iter() mirrors moka::Cache::iter() and yields (Arc<K>, V) pairs. Unlike moka’s lazy iterator, the snapshot is captured up front (so it survives concurrent mutations) and may include entries that are expired but not yet evicted, matching moka’s semantics.
All time checks use wacore::time::now_millis instead of std::time::Instant, making it compatible with environments where monotonic clocks are unavailable.

CacheStore trait

Each logical cache uses a unique namespace string (e.g., "group", "device", "lid_pn_by_lid"). Implementations should partition keys by namespace — for example, a Redis implementation might prefix keys as {namespace}:{key}. Cache operations are best-effort. The client falls back gracefully when cache reads fail (treats as miss) and logs warnings on write failures.

TypedCache

TypedCache<K, V> is a generic wrapper that dispatches to either moka or a custom CacheStore backend. The moka path has zero extra overhead — values are stored in-process without any serialization. The custom-store path serializes values with serde_json and keys via Display.
CacheEntryConfig provides a build_typed_ttl convenience method that automatically selects the right backend: if a custom CacheStore is provided, it creates a TypedCache backed by the store; otherwise it falls back to an in-process moka cache.
The group cache stores Arc<GroupInfo> so that warm sends and repeated query_info calls reuse the same snapshot instead of deep-cloning the participants list.

invalidate_all and clear

TypedCache provides two ways to remove all entries:
  • invalidate_all() — synchronous. For moka backends this works immediately. For custom CacheStore backends, it spawns a fire-and-forget task via tokio::runtime::Handle::try_current(), which requires the tokio-runtime feature. Without tokio-runtime enabled, the clear is skipped and a warning is logged.
  • clear() — async. Awaits completion for custom backends and is the recommended approach when you need to ensure all entries are removed.
If you disable the tokio-runtime feature and use a custom CacheStore backend, invalidate_all() will silently skip clearing the external store. Use the async clear() method instead.

CacheStores configuration

The CacheStores struct controls which caches use custom backends:
Fields left as None keep the default moka behavior. Use CacheStores::all(store) to set the same backend for all pluggable caches at once.
Coordination caches (session_locks, chat_lanes), the signal write-behind cache, and pdo_pending_requests always stay in-process — they hold live Rust objects (mutexes, channel senders) that cannot be serialized to an external store.

Usage with Bot builder

Or use CacheStores::all() to route all pluggable caches to the same backend:
See Custom backends guide for a full implementation example.

Granular cache patching

Instead of invalidating a cache entry and re-fetching from the server on every change notification, whatsapp-rust applies granular patches to cached values in place. This eliminates an extra IQ round-trip per update and keeps caches consistent in real time.

How it works

All patching follows the same pattern: read the cached value, mutate it, and write it back. There is no atomic compare-and-swap — the get → mutate → insert sequence can race with concurrent notifications, but this is acceptable because the cache is best-effort and a full server fetch on the next read corrects any drift.

Patched cache domains

Granular patching is implemented in three areas: Device registry (src/client/device_registry.rs) When a device notification arrives, the client patches the device_registry_cache (keyed by user string, stores DeviceListRecord):
  • patch_device_add — appends a new device JID to the cached list and persists the updated DeviceListRecord to the backend store
  • patch_device_remove — removes a device by ID using retain, then persists
  • patch_device_update — updates key_index on an existing device entry, then persists
All three methods iterate over every known PN/LID alias for the user so stale alternate-key entries stay consistent. Device patches also persist to the backend store immediately, so changes survive cache eviction and restarts. The patch_device_add method also performs ADV (Account Device Verification) key index filtering. When KeyIndexInfo is present, the signed bytes are decoded via wacore::adv::decode_key_index_list to extract valid device indexes, and stale devices not in the valid set are filtered out. If the raw_id in the notification differs from the stored value, the client detects an identity change and clears all Signal sessions for that user’s non-primary devices. When a notification arrives with only a hash (no device list), the client falls back to full invalidation and lets the next access re-fetch from the server. LID migration: When a new LID-PN mapping is discovered, the device registry re-keys entries from the PN key to the LID key via migrate_device_registry_on_lid_discovery(). This ensures lookups by either addressing scheme resolve to the same canonical record. The migration also invalidates stale PN-keyed entries from both cache and database. Group metadata (src/handlers/notification.rs, src/features/groups.rs) When participant add/remove notifications arrive, the cached GroupInfo is patched in place:
  • Participant adds use GroupInfo::add_participants(), which deduplicates by user and backfills LID-to-PN maps for LID-addressed groups
  • Participant removes use GroupInfo::remove_participants(), which also cleans up both LID-to-PN and PN-to-LID maps bidirectionally
  • API calls (client.groups().add_participants(), client.groups().remove_participants()) also patch the cache after a successful server response, filtering to only participants the server accepted (status 200)
Group patches are cache-only — they are not persisted to the backend. If the cache entry is evicted, the next query_info() call re-fetches from the server. Only leave() uses full invalidation. LID-PN mappings (src/lid_pn_cache.rs) The LidPnCache uses timestamp-based conflict resolution when adding new mappings. The PN → entry map only updates if the new entry’s created_at is newer than or equal to the existing entry’s, preventing older stale mappings from overwriting newer ones.

Patching vs. invalidation summary

Architecture

Understand PersistenceManager’s role

Authentication

Learn how session data is persisted

Custom Backends

Implement your own storage backend

Storage API

Complete storage API reference