> ## Documentation Index
> Fetch the complete documentation index at: https://whatsapp-rust.jlucaso.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Inbound Durability Hook

> Commit encrypted inbound messages before acknowledgment, within backend and retention limits

> [!NOTE]
>
> Examples on this page target [source snapshot `7e5c198e`](https://github.com/oxidezap/whatsapp-rust/tree/7e5c198e1a25ea405faa7a69a47bc727ea15484c), not a crates.io release. Use the [current API guide](https://whatsapp-rust.jlucaso.com/guides/current-api.md) to select the matching dependency.

## Overview

Without a hook, acknowledgment does not wait for your application's durable commit. A process failure between acknowledgment and your write can lose the application copy.

Register `InboundDurabilityHook` to commit encrypted direct and group messages before their transport acknowledgments. The SDK first writes a pending copy, flushes Signal state and awaits your hook. Return `Ok(())` only after your commit is durable. A hook error suppresses acknowledgment; a later redelivery can use a retained pending copy.

This guarantee depends on successful pending-buffer storage and retention. It does not cover every `Event::Messages` origin, guarantee server redelivery, or provide exactly-once processing. Read the failure and origin limits below before choosing this hook for your application's inbox.

## Batching

Live traffic is delivered to the hook one message at a time — a batch of one, committed immediately, so latency is unchanged from the previous per-message behavior.

During the **offline drain** (the backlog replayed on reconnect), the client accumulates decrypted messages and commits them as a batch, mirroring WhatsApp Web's `MessageProcessorCache` granularity. A batch flushes on whichever trigger fires first:

| Trigger | Value |
| - | - |
| Message count | 400 |
| Encoded size | 4 MiB |
| Timeout since first buffered message | 3 seconds |
| End of drain / disconnect / reconnect | forced flush |

These triggers are internal constants, not currently exposed as configuration. The message-count trigger matches WhatsApp Web's `web_message_processing_cache_size` (the snapshot flush granularity — distinct from the 200-stanza `<offline_batch>` server pull size). The drain→live transition is raceless: the tail batch of the drain always commits before any live-mode message is processed, so a consumer never observes drain and live messages out of order across the boundary.

The normal batch path writes the durable buffer, flushes Signal state, calls your hook, publishes `Event::Messages`, conditionally clears pending rows, then permits acknowledgments and offline delivery receipts. Do not treat that sequence as one transaction across your backend and the server. An error during acknowledgment can leave some acknowledgments already sent. Make the consumer commit idempotent and keep application recovery independent of event callback delivery.

> [!NOTE]
>
> Offline delivery receipts are flushed once **per durable drain batch**, not only at the end of the full offline drain, matching WA Web's `createSnapshot` → `sendAggregateOfflineReceipts` per snapshot. This bounds the receipt buffer over a large backlog and caps redelivery on a mid-drain disconnect to a single snapshot instead of the whole backlog.

Once your hook returns `Ok`, the dispatched `Event::Messages` carries `hook_committed: true` on its [`MessageBatch`](https://whatsapp-rust.jlucaso.com/concepts/events#messages) — a marker for another consumer of the same event stream, not an instruction to skip anything: a hook that persists somewhere other than that consumer's own store still needs it to materialize every batch. An application-level store that materializes this same event stream can use the flag to avoid double-processing a hook-fed batch.

## Opting In

```rust theme={null}
use whatsapp_rust::{InboundDurabilityHook, prelude::*};
use async_trait::async_trait;
use std::sync::Arc;

struct MyStore { /* your DB connection */ }

#[async_trait]
impl InboundDurabilityHook for MyStore {
    async fn on_messages(
        &self,
        _client: Arc<Client>,
        batch: &[InboundMessage],
    ) -> anyhow::Result<()> {
        // Ideally a single INSERT/transaction over the whole batch. This
        // loop commits per item instead, so a failure partway through (the
        // `?` on a later item) leaves earlier items already durably
        // committed — yet the SDK still suppresses every ack and redelivers
        // the whole batch on Err. `my_db_insert` MUST be an idempotent
        // upsert (e.g. `INSERT ... ON CONFLICT DO NOTHING`) so that replay
        // of an already-committed item is a no-op, not a duplicate.
        for item in batch {
            my_db_insert(&item.info.id, &item.message).await?;
        }
        Ok(())
    }
}

let bot = Bot::builder()
    .with_backend(SqliteStore::open("whatsapp.db").await?)
    // Opt in — without this call the client keeps its default at-most-once behavior.
    .with_inbound_durability_hook(MyStore { /* ... */ })
    .on_message(|ctx| async move {
        // Event handlers still fire once per message, in arrival order;
        // the ack is deferred in the background.
        println!("received: {}", ctx.info.id);
    })
    .build()
    .await?;
```

## The `InboundDurabilityHook` Trait

```rust theme={null}
use async_trait::async_trait;
use std::sync::Arc;
use whatsapp_rust::wacore::types::events::InboundMessage;

#[async_trait]
pub trait InboundDurabilityHook {
    async fn on_messages(&self, client: Arc<Client>, batch: &[InboundMessage]) -> anyhow::Result<()>;
}
```

| Parameter | Description |
| - | - |
| `client` | The active client — use it for lookups, **not** for sending to a sender present in the batch (see [Caveats](#caveats)). |
| `batch` | The decrypted messages to commit, in arrival order. A batch of one on live traffic; possibly many during the offline drain. |

Each `InboundMessage` carries:

```rust theme={null}
#[derive(Debug, Clone, Serialize, bon::Builder)]
#[non_exhaustive]
pub struct InboundMessage {
    pub message: Arc<wa::Message>,
    pub info: Arc<MessageInfo>,
}
```

Return `Ok(())` once the whole batch is durably committed. Return `Err` to suppress every ack in the batch.

`InboundMessage`, `MessageBatch`, and `BatchOrigin` are re-exported from the crate `prelude`.

## Idempotency Requirement

If a pending copy remains and the server redelivers after a crash, the hook can run again for a message your consumer already committed. Make the hook idempotent. A partially acknowledged batch may replay only in part, so repeated items and partially applied consumer commits must be safe to retry independently.

Deduplicate by the full triplet `(info.source.chat, info.source.sender, info.id)` — **not** `info.id` alone. Stanza IDs are only unique within a `(chat, sender)` pair, so two different chats can reuse the same ID string.

```rust theme={null}
// Correct idempotency key, per item in the batch
let key = (
    item.info.source.chat.to_string(),
    item.info.source.sender.to_string(),
    item.info.id.clone(),
);

// Wrong — id alone is not globally unique
let key = item.info.id.clone();
```

In SQL, a `UNIQUE` constraint or `INSERT OR IGNORE` on `(chat, sender, id)` is the most robust approach.

## How Redelivery Works

When the server redelivers a message the client previously did not ack:

1. The client detects the duplicate stanza.
2. If a hook is registered and a buffered copy exists in `pending_inbound_messages`, the message re-enters the commit pipeline (it can be grouped into the same batch as other stanzas being processed at the time) and the hook runs from the buffered copy.
3. On `Ok` the buffer row is cleared and the message is acked.
4. On `Err` the buffer is kept; the hook runs again on the next redelivery.
5. If no buffered copy exists (genuine duplicate already committed), the message is acked directly without invoking the hook.

A 7-day retention sweep removes rows that a permanently-failing hook would otherwise leak. Rows that reach their TTL without being cleared are deleted, and if the server redelivers after that point the message degrades to at-most-once.

## Backend Requirement

Durable cross-crash replay requires a backend that implements the pending-inbound methods on `ProtocolStore`:

* `store_pending_inbound` — write the decrypted message bytes before the hook runs
* `get_pending_inbound` — read the buffer on redelivery
* `delete_pending_inbound` — clear the buffer after the hook commits
* `delete_expired_pending_inbound` — retention sweep (called unconditionally from keepalive)

Two additional batch-oriented methods, `store_pending_inbound_batch` and `delete_pending_inbound_batch`, default to looping the single-row methods above, which does not make an arbitrary custom backend transactional. The bundled `SqliteStore` overrides both to commit a whole batch in one transaction — see [Custom Backends](https://whatsapp-rust.jlucaso.com/guides/custom-backends.md#preserve-durability) if you want the same atomicity in your own backend.

With an inbound hook configured, construction probes pending-inbound store, read and delete operations. A failed probe returns `UnsupportedDurabilityBackend` from the builder. Passing that probe does not certify batch atomicity, crash durability or retention behavior. Implement the [bounded reads and conditional mutations](https://whatsapp-rust.jlucaso.com/guides/custom-backends.md#bounded-pending-message-storage) as well as the legacy methods, and test those properties in your backend.

## Caveats

> [!WARNING]
>
> **Duplicates are possible.** A crash after your consumer commits but before the ack lands can lead to another hook invocation if a pending copy remains and the server redelivers. Neither replay nor whole-batch redelivery is guaranteed. Make your hook idempotent (deduplicate by `(chat, sender, id)`).

**Backpressure.** The hook is awaited inside the receive pipeline. A slow hook backpressures inbound processing for the duration of the commit — the same trade-off as whatsmeow's synchronous ack. Persist and return; spawn any reply logic after the hook returns `Ok`.

**No synchronous sends to a sender in the batch.** During 1:1 message processing the per-sender Signal lock is held. Performing a synchronous client operation to a sender present in the batch (e.g. a blocking reply) will deadlock. Use `tokio::spawn` if you need to reply from within the hook.

**Scope.** The hook covers end-to-end encrypted messages (1:1 and group). Newsletter and broadcast channel messages use a separate ack path and are never gated by the hook — they dispatch `Event::Messages` directly. PDO placeholder recoveries (`info.unavailable_request_id` set) bypass the hook the same way.

**Buffer-write failure.** The same Client retains encoded plaintext across cancellation and reconnect so redelivery can retry persistence without advancing Signal again. A process exit loses resident-only copies. See [retained plaintext](#retained-plaintext-on-current-main) for admission bounds and cleanup ordering.

**Redelivery `info` fields.** On a redelivery replay, `info` is re-parsed from the stanza. A few fields derived during the first dispatch (the ephemeral timer, encrypted comment threading) may be absent. The `message` body is always the original.

**Event callbacks can receive duplicates.** The same Client suppresses repeated publication while its dispatch claim survives. Process restart, expiry or eviction can allow another event if a retained pending copy is replayed. Keep event handlers idempotent independently of the hook.

**Resent messages get their own, separate gate.** The redelivery handling above covers a byte-identical stanza the server replays. A sender-side outbox retry instead re-encrypts the same message under a new sender-key iteration, so it isn't byte-identical and reaches the pipeline as an apparently-fresh decrypt. Since [#1352](https://github.com/oxidezap/whatsapp-rust/pull/1352), an in-memory dispatch-once gate (`dispatched_messages` in `CacheConfig`, default 5-minute TTL) collapses that case to one `Event::Messages` too — see [Resend collapse](https://whatsapp-rust.jlucaso.com/concepts/events.md#messages). Unlike the pending-inbound buffer, this gate has no durable backing and does not survive a restart of your process, so it narrows the window for a duplicate dispatch rather than closing it: your hook and event handlers still need their own idempotency for the reasons above.

## Full Example

The repository ships `examples/durability_hook.rs` — a file-backed archiver that appends each message in a batch to disk with a single `fsync` before returning `Ok`, and seeds the deduplication set from the archive on startup so dedupe survives a restart.

```bash theme={null}
cargo run --example durability_hook
```

Key patterns from that example:

```rust theme={null}
#[async_trait::async_trait]
impl InboundDurabilityHook for InboxArchiver {
    async fn on_messages(
        &self,
        _client: Arc<Client>,
        batch: &[whatsapp_rust::types::events::InboundMessage],
    ) -> anyhow::Result<()> {
        // Live traffic arrives one message at a time; an offline drain hands
        // over a whole batch. Either way the commit below is a single append +
        // fsync. A production archive must also handle partial writes on restart.
        let mut lines = String::new();
        let mut keys: Vec<CommitKey> = Vec::with_capacity(batch.len());
        {
            let seen = self.seen.lock().map_err(|_| anyhow::anyhow!("seen lock poisoned"))?;
            for m in batch {
                let key: CommitKey = (
                    m.info.source.chat.to_string(),
                    m.info.source.sender.to_string(),
                    m.info.id.clone(),
                );
                // Dedup against the archive AND earlier entries of this same
                // batch, so one fsync can never append a key twice.
                if seen.contains(&key) || keys.contains(&key) {
                    continue;
                }
                let preview = m.message.conversation.as_deref().unwrap_or("<non-text>").replace(['\t', '\n'], " ");
                lines.push_str(&format!("{}\t{}\t{}\t{preview}\n", key.0, key.1, key.2));
                keys.push(key);
            }
        }

        if !keys.is_empty() {
            // Append and fsync on a blocking thread. This is not an atomic
            // transaction: restart recovery must handle a partial tail. Returning Ok after sync_all means
            // "safe to ack every message"; any error returns Err, so the acks
            // are suppressed. Redelivery is possible, not guaranteed.
            let file = Arc::clone(&self.file);
            tokio::task::spawn_blocking(move || -> std::io::Result<()> {
                let mut f = file.lock().expect("file lock poisoned");
                f.write_all(lines.as_bytes())?;
                f.sync_all()
            }).await.map_err(|e| anyhow::anyhow!("archive write task failed: {e}"))??;

            let mut seen = self.seen.lock().map_err(|_| anyhow::anyhow!("seen lock poisoned"))?;
            for key in keys {
                seen.insert(key);
            }
        }
        Ok(())
    }
}
```

> [!TIP]
>
> Always use `tokio::task::spawn_blocking` for disk I/O inside the hook. Blocking calls on the async thread stall the entire receive pipeline, including the batch that is waiting to commit.

## See also

* [Retry admission](https://whatsapp-rust.jlucaso.com/advanced/retry-admission.md) configures inbound repair and outbound decrypt-failure policies before client assembly.
* [History Sync Admission Hook](https://whatsapp-rust.jlucaso.com/advanced/history-sync-admission.md) — the sibling opt-in policy for rejecting inbound history-sync chunks before the major-sync queue.

## Current references and replay

Use `InboundMessage::message_ref()` for chat actions and `newsletter_ref()` for channels. Construct non-exhaustive inbound DTOs with builders in host fixtures. Preserve wildcard arms when matching extensible enums. See [current contracts](https://whatsapp-rust.jlucaso.com/guides/current-api.md#hooks-and-backend-reads).

PDO placeholder recovery remains event-only. A later encrypted retry still must complete its durability hook even when the equivalent user event was already dispatched. The retry can promote that recovery to committed state without publishing the same event again. Distinct user payloads in an SKDM-bearing retry retain separate dispatch claims; adding an SKDM envelope does not make their user content identical. Hooks and event consumers still need idempotent `(chat, sender, id)` handling.

[PDO retry and durability regression scenarios](https://github.com/oxidezap/whatsapp-rust/blob/7e5c198e1a25ea405faa7a69a47bc727ea15484c/src/message/tests.rs)

## Retained plaintext on current main

On [main snapshot `7e5c198e`](https://github.com/oxidezap/whatsapp-rust/blob/7e5c198e1a25ea405faa7a69a47bc727ea15484c/src/types/durability_hook.rs), plaintext retention provides recovery within the same Client after a buffer-write failure. Admission reserves encoded backing before Signal decryption under a 4 MiB budget and 400 reservations. The budget includes carrier, consumer projection and metadata, so the maximum accepted ciphertext is smaller than 4 MiB. Capacity refusal leaves Signal untouched and sends no positive ACK. Oversized stanzas remain refused under this bound.

If persistence fails, the same Client owns an encoded plaintext copy across cancellation and reconnect. Redelivery can retry storage without advancing Signal again. This is resident retention, not disk persistence: a process exit loses copies that never reached durable pending storage. Decoded graphs held by active processing, callbacks and consumers are outside this backing budget.

The pending envelope retains the consumer projection, including a resolved secret-message payload. Bounded exact/group-alias reads and revision-conditional replacement/deletion are now required by the backend probe. See [custom backend requirements](https://whatsapp-rust.jlucaso.com/guides/custom-backends.md#bounded-pending-message-storage).

After the hook commits, event publication precedes conditional pending-row cleanup. ACK waits for cleanup to complete. An error or cancellation can therefore leave a pending row after the event already fired. The same Client's dispatch cache survives reconnect and suppresses repeated events within its retention window; a process restart still needs your durable deduplication by `(chat, sender, id)`. Neither that cache nor the hook provides exactly-once delivery.

Message durability, [history capture](https://whatsapp-rust.jlucaso.com/guides/rust-api-migration.md#separate-history-capture-from-message-commits) and [group notification capture](https://whatsapp-rust.jlucaso.com/api/groups.md#durable-notification-capture) require separate registration. Enabling one does not enable the others.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.