# Offline send, receive, and reconciliation (https://docs.open-e2ee.dev/build/offline-and-reconciliation.md)

- Status: stable
- Applies to: 15.0.0
- Platforms: Expo · Browser · Node
- Prereqs: A working client from Start → Quickstart
- Reading time: 10 min

Encrypted messaging is offline-first whether you planned for it or not. A ratchet
is local state that advances with each encryption and decryption. After a week
offline, a device does not only have a stale cache. It also holds a different
position in a shared cryptographic sequence.

This page explains SDK behavior and application responsibilities.

## The SDK does not own an outbox [#the-sdk-does-not-own-an-outbox]

There is no send queue in `@open-e2ee/signal-protocol-sdk`. `send(recipientUserId, content)`
and `encryptMessage(remoteAddress, plaintext)` attempt the operation now and throw
if they cannot complete it. If the user is on a train, your application must
remember the composed message.

The same responsibility boundary applies here:

> "The client owns protocol coordination; the host application owns persistence,
> authentication, authorization, and product policy."

An outbox combines persistence and policy. Your application determines the retry
period and what to show after attempt six. It also determines how to handle a
message that remains pending for two days. The SDK cannot make these product
decisions.

What it gives you instead is a retry primitive with sane bounds:

```ts
import { withRetry } from '@open-e2ee/signal-protocol-sdk/utils/retry';

await withRetry(() => signal.send(recipientUserId, body), {
  operationName: 'send',
  maxRetries: 2,
  baseDelay: 1000,
  maxDelay: 10000,
});
```

`withRetry` is for a single operation crossing a flaky network. It is not a
durable queue and it does not survive a process restart. Your outbox rows need to
live in your own database, next to the decrypted message rows you already own.

> **Tradeoff — Encrypt at compose time or at flush time**
>
> Encryption at compose time produces ciphertext before connectivity returns. It
> also advances the sending ratchet immediately. If you later reorder, deduplicate,
> or drop that queued item, the recipient sees the unused message number as a gap.
>
> Encryption at flush time keeps the outbox as plaintext application rows. You can
> edit and reorder the queue, but the local database stores plaintext until send
> time. The SDK does not select either approach. Decide whether an editable outbox
> or an opaque queue at rest is more important for your product.

## Out-of-order and skipped messages [#out-of-order-and-skipped-messages]

The Double Ratchet handles gaps by deriving and storing the message keys it
skipped over, so a message that arrives late still decrypts. The bounds are
configurable on `ratchetConfig` and default to:

| Option | Default | What it bounds |
|---|---|---|
| `maxSkip` | `25000` | How far ahead of the last received counter a message may be |
| `maxMessageKeysStored` | `2000` | How many skipped keys each receiver chain keeps |
| `keyExpirationMs` | `604800000` (7 days) | How long a skipped key is kept before it is dropped |

Separately, `MAX_UNACKNOWLEDGED_SESSION_AGE_MS` is 30 days. The SDK treats an
unanswered prekey session as stale after that period.

These limits define the edge of "messages arrive eventually". A device can miss
more than 25000 messages in one chain. It can also return after eight days for a
key that expired after seven days. Both cases produce an error instead of a retry.

> **Failure mode — TOO_MANY_SKIPPED_MESSAGES and MESSAGE_DUPLICATE**
>
> Both surface as an `EncryptionError` whose `.code` is `TOO_MANY_SKIPPED_MESSAGES`
> for the chain gap. After cleanup deletes an expired skipped key, its counter is
> below the current receive counter. The SDK then reports `MESSAGE_DUPLICATE`
> through `DuplicatedMessageError` because it cannot distinguish that expired key
> from a consumed key. Neither case is recoverable by retrying the ciphertext.
>
> A relay redelivery, a batch replay after a crash, a null message, and a copy of a
> failed message after the application got that message from another copy are all
> normal. `processIncomingEnvelope()` returns the `duplicate` or `null-message`
> outcome for them. Treat each as a message-layer no-op. Do not show it as a user
> error.
>
> What you cannot do is tell the user which of these happened in a way they can act
> on. The useful product behavior is a gap marker in the thread plus a structured
> log line, not a modal.

## Catching up after reconnect [#catching-up-after-reconnect]

One subscription covers live delivery.

`startRelaySubscription()` starts local decryption. The same subscription
handles retry requests. When a peer cannot decrypt your message, it sends a
`retry_request` envelope to your device through the relay. Your client then
resends the message only to the device that asked. `stopRelaySubscription()`
ends the subscription. `stop()` shuts down the complete client.

For a backlog, process the pulled envelopes in one batch rather than one call per
message. A pulled batch can hold a `retry_request` envelope from a peer. Give the
batch to `receiveIncomingEnvelopes()`:

```ts
// pullMailbox() and acknowledge() are your transport code.
const pendingEnvelopes = await pullMailbox();
const { processedMessageIds, failedMessageIds } =
  await signal.receiveIncomingEnvelopes(pendingEnvelopes);

for (const id of processedMessageIds) await acknowledge(id);
// Do not acknowledge failedMessageIds. A later pull gives them again.
```

`receiveIncomingEnvelopes()` requires the `onMessageDecrypted` hook. The client
does not give the hook a delivery receipt, a typing indicator, a sender-key
distribution, a profile-key update, a null message, or a `GroupKeySync` from an
own device. It gives all other
decrypted content to the hook. It handles each retry request.
`processedMessageIds` are ready for acknowledgment. They include each envelope
that the client drops as a duplicate. The client keys a received message by its
sender and its timestamp only. A later message from any device of the same
sender with the same timestamp drops with no notice, and `onMessageDecrypted`
does not run for it. The rule also covers sent transcripts from two own devices
in two conversations. The method does not throw after the first
failure. One invalid envelope therefore does not block the next ninety
envelopes. A `SignalProtocolRelayServer` adapter acknowledges one envelope with
`markDelivered(envelopeId)`.

The method also sorts prekey messages before ordinary ciphertexts. A prekey message
establishes the session that later messages require. Use
`decryptMessages(remoteAddress, ciphertexts)` for a single peer's batch.

Do not give a pulled batch to `processIncomingEnvelopes()`. It does not handle a
retry request. It returns an `INVALID_CIPHERTEXT` error for a `retry_request`
envelope. The peer therefore never gets its resend.

Read `client.relayConnectionState` for the connection itself. Its `state` is
`stopped`, `connecting`, `connected`, or `reconnecting`, and
`subscribeRelayConnectionState(listener)` reports each transition. A `stopped`
state with the reason `upgrade-required` does not recover by itself. The
subscription does not reconnect and does not pull. Only a newer SDK can connect
again. See [protocol versions](https://docs.open-e2ee.dev/signal-relay/protocol-versions.md). On React
Native, `useSignalProtocolRelayLifecycle` stops the subscription in the background and starts
it again when the app becomes active. The OpenE2EE Signal Protocol Relay then replays retained messages
over the new socket.

A hosted client accepts an ephemeral message only after its work succeeds. A
durable message whose work fails stays in the mailbox. The client gets it again
on the next recovery pull or socket replay. The client continues with the next
message at once, so it does not keep the order across a failed message. While a
failed message remains, the client pulls again after a random wait. That wait is
from half to one and a half of the failed-work wait, which starts at 2 s and
doubles to 64 s.

Read `client.syncStatus` for the initial sync. Its value is
`'synced' | 'failed' | 'none'`. The `'none'` value means that you did not configure a relay.
The `'failed'` value means that the sync did not complete. Call the idempotent
`syncToServer()` method again to recover.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| Application outbox rows (app-owned) | yes | no | no | no |
| Envelope ciphertext | yes | yes | no | size, sender/recipient routing, arrival time |
| Skipped message keys (`maxMessageKeysStored`) | yes | no | no | no |
| Session record (`version: 4`) | yes | no | no | no |
| `client.syncStatus` | yes | no | no | no |
| `markAsRead(messageId)` state | yes | no | no | no |
| `sendReadReceipt(recipientUserId, timestamps)` payload | yes | yes | no | that a receipt moved, by its `contentKind` label `receipt` |
| Decrypted plaintext from `onMessageDecrypted` | yes | no | no | no |

## Reconciliation converges. It does not commit [#reconciliation-converges-it-does-not-commit]

This is the part that surprises teams coming from a server-authoritative stack.
With a central database, two conflicting edits arrive at one place and one of them
wins at a known instant. With end-to-end encryption there is no such place. The
relay never needs message plaintext or device private keys, which also means it
cannot arbitrate anything that depends on reading them. Every device reaches
agreement on its own schedule from the operations it received.

This model provides no global order for business logic. It also provides no
server-side "last write wins" behavior for encrypted fields. Two devices can show
different states while both operate correctly. The users' offline periods, not
your infrastructure, bound this window.

> **Tradeoff — Op-log growth under encryption**
>
> The standard fix for an ever-growing operation log is server compaction: the
> server reads the log, collapses superseded operations, and ships a snapshot. A
> relay cannot do that here, because compaction requires understanding what each
> operation means.
>
> The log and cold-sync cost therefore grow together. You can use client-side
> snapshots. A device periodically writes an encrypted checkpoint, which the relay
> stores as opaque data. The relay serves this checkpoint instead of the complete
> log. You must build and version this system.
>
> You can instead set a fixed retention limit. Older operations then expire. A
> device that exceeds the limit must resync from a checkpoint or start clean. Both
> options have costs. Choose before a user accumulates 200,000 operations.

> **Not covered — Recovery of history a device never had**
>
> Nothing on this page recovers messages that arrived before a device existed.
> [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md) addresses that
> different problem. Its answer is a product policy decision, not a reconnect
> strategy.

The SDK is `15.0.x`. Public APIs and persisted formats follow semantic versioning.

## Next [#next]

- [Recovery, backup, and migration](https://docs.open-e2ee.dev/build/recovery-backup-migration.md): what happens to history a device was never present for
- [Error handling](https://docs.open-e2ee.dev/operate/error-handling.md): the full error taxonomy behind `TOO_MANY_SKIPPED_MESSAGES` and related errors
- [Local-first architecture](https://docs.open-e2ee.dev/learn/local-first.md): why convergence, not commit, is the model
- [Offline, recovery, and identity change](https://docs.open-e2ee.dev/guides/offline-recovery-identity-change.md): an end-to-end worked example
