# Error handling and retries (https://docs.open-e2ee.dev/operate/error-handling.md)

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

Encrypted messaging fails differently from the rest of your application. You can repeat a failed HTTP call. You usually cannot repeat a failed decrypt because the attempt advances a state machine. This page covers the taxonomy the SDK throws, which parts of it are worth retrying, and what recovery actually means.

## The base class [#the-base-class]

Every error in the `EncryptionErrorCode` family extends `EncryptionError`. The
class extends `Error` and adds three fields:

- `.code`: a stable `EncryptionErrorCode` value. This is the field you branch on.
- `.context`: structured context about the operation. Safe to log after redaction. See [observability](https://docs.open-e2ee.dev/operate/observability.md).
- `.originalError`: the underlying cause, if a wrapper supplied it.

## The code taxonomy [#the-code-taxonomy]

**Session**

| Code | Meaning | What it implies |
|---|---|---|
| `SESSION_NOT_FOUND` | No session exists for the address | Establish one |
| `SESSION_CORRUPTED` | Session data is invalid | Delete and re-establish |

**Message**

| Code | Meaning | What it implies |
|---|---|---|
| `INVALID_CIPHERTEXT` | Malformed message format, or a `retry_request` envelope given to `processIncomingEnvelope()` | Drop malformed ciphertext. Give a `retry_request` envelope to `receiveIncomingEnvelopes()` |
| `DECRYPTION_FAILED` | Could not decrypt | Inspect session state |
| `ENCRYPTION_FAILED` | Could not encrypt | Inspect session state |
| `MESSAGE_DUPLICATE` | No retained key exists below the current counter. For a message that this client processed or that gives no content, `processIncomingEnvelope()` returns the `duplicate` or `null-message` outcome instead | Discard |
| `TOO_MANY_SKIPPED_MESSAGES` | Skip bound exceeded | Reset session |

**Identity and trust**

`UNTRUSTED_IDENTITY` requires an explicit trust decision when a candidate no
longer matches the pinned tuple. `IDENTITY_MISMATCH` and
`SIGNATURE_VERIFICATION_FAILED` are integrity failures. Reject their input and
inspect the operation.

**Prekey and establishment**

`INVALID_PREKEY_BUNDLE`, `PREKEY_NOT_FOUND`, `PREKEY_ROTATION_REQUIRED`.

**Ratchet**

`COUNTER_OVERFLOW`, `INVALID_DH_KEY`.

**Storage**

`KEY_STORAGE_ERROR` wraps a key-storage failure. `STORAGE_QUOTA_EXCEEDED` means
that the disk or the storage quota is full. The rejected write does not persist,
and the store stays open. Inspect the first error's cause. Free space before
retrying the second.

## Specialized classes and their guards [#specialized-classes-and-their-guards]

Use the exported type guards to centralize narrowing and keep call sites stable.
The current guards delegate to `instanceof`, so they require one loaded copy of
the SDK. Do not bundle duplicate package instances.

| Class | Guard | Extra fields |
|---|---|---|
| `UntrustedIdentityError` | `isUntrustedIdentityError()` | `.untrustedAddress`, `.identity` |
| `DuplicatedMessageError` | `isDuplicatedMessageError()` | `.duplicatedAddress`, `.counter?`, `.epoch?`, `.fingerprintPreview?` |
| `SealedSenderAuthError` | `isSealedSenderAuthError()` | — |
| `PQXDHRequiredError` | `isPQXDHRequiredError()` | `.remoteAddress`, `.reason`, `.retryable`, `.suggestedRetryDelay?` |
| `StorageQuotaExceededError` | `isStorageQuotaExceededError()` | — |

`PQXDHRequiredError` is what a peer with no post-quantum material looks like under the `postQuantum: 'required'` policy, which is the only policy. It is a fail-closed outcome, not a fault. See [upgrades](https://docs.open-e2ee.dev/operate/upgrades.md).

## Identify a "Bad MAC" failure [#identify-a-bad-mac-failure]

There is **no** class named `BadMacError` in this SDK. The classic `libsignal` "Bad MAC" failure surfaces as `DECRYPTION_FAILED`. If you search your logs for `BadMac`, you will find nothing and conclude the problem is elsewhere. Search for the code.

> **Failure mode — Bad MAC stops delivery without stopping the process**
>
> In February 2026 a gateway integration recorded a burst of 479 Bad MAC exceptions from libsignal, after which "WhatsApp inbound message delivery silently stops. The gateway believes it is connected and listening, making this a silent failure."
>
> That is the shape to design against. The subscription is healthy, the socket is open, and the process is up. However, the subscription received no messages for an hour. A separate project logged 168,000+ errors in two hours across 400+ sessions. The errors exhausted the Node heap and continued after session file deletion.
>
> Two defenses, both cheap: alert on *absence* of successful decrypts per subscription, not on error rate alone. And bound your per-peer recovery attempts so a corrupt session cannot spin.

## Dispatching [#dispatching]

```ts
import {
  EncryptionError,
  EncryptionErrorCode,
  ProtocolAddress,
  isUntrustedIdentityError,
} from '@open-e2ee/signal-protocol-sdk';
// The remaining narrowing guards live on the /types subpath, not the package root.
import {
  isDuplicatedMessageError,
  isPQXDHRequiredError,
  isStorageQuotaExceededError,
} from '@open-e2ee/signal-protocol-sdk/types';

async function handleEncryptionError(client, remoteAddress: ProtocolAddress, error: unknown) {
  if (!(error instanceof EncryptionError)) throw error;

  // 1. Human trust decisions. Never automatic.
  if (isUntrustedIdentityError(error)) {
    await ui.showIdentityChanged({
      userId: error.untrustedAddress.userId,
      deviceId: error.untrustedAddress.deviceId,
      identity: error.identity,
    });
    return;
  }

  // 2. Outcomes with a defined move that is not an error to the user.
  if (isDuplicatedMessageError(error)) {
    return; // consumed or expired skipped key
  }
  if (isPQXDHRequiredError(error)) {
    await ui.showPeerCannotReceive(error.remoteAddress, error.reason);
    return;
  }
  if (isStorageQuotaExceededError(error)) {
    await storage.freeSpaceThenRetry();
    return;
  }

  // 3. Codes.
  switch (error.code) {
    case EncryptionErrorCode.MESSAGE_DUPLICATE:
      return; // group paths can raise the base class with this code
    case EncryptionErrorCode.SESSION_CORRUPTED:
      await client.deleteSession(remoteAddress);
      return;
    case EncryptionErrorCode.TOO_MANY_SKIPPED_MESSAGES:
      await ui.showMessageUnavailable(remoteAddress);
      return;
    case EncryptionErrorCode.DECRYPTION_FAILED:
      metrics.increment('signal.decrypt.failed', { code: error.code });
      return;
    default:
      client.logger.error?.('Unhandled Signal Protocol error', error, { code: error.code });
  }
}
```

Note the ordering. Specialized guards run before the code switch because an `UntrustedIdentityError` also carries a code. A generic branch would otherwise swallow it.

## What to retry, and what never to retry [#what-to-retry-and-what-never-to-retry]

`/utils/retry` exports `withRetry(fn, options)` with `operationName`, `maxRetries`, `baseDelay`, `maxDelay`, and `enableJitter`. It also exports `isRetryableError(error)`, which encodes the SDK's own view.

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

await withRetry(() => client.syncToServer(), {
  operationName: 'syncToServer',
  maxRetries: 2,
  baseDelay: 2000,
  maxDelay: 30000,
});
```

**Retryable.** Network and timeout failures, database lock and busy conditions, and transient race conditions. These are I/O problems wearing a crypto costume. `syncToServer()`, `rotatePreKeys()`, and prekey bundle fetches belong here.

**Retried once by the SDK.** A `user-visible` or `background-sync` send can receive 503 `DELIVERY_UNCERTAIN` from the OpenE2EE Signal Protocol Relay: the delivery was neither confirmed nor refused. The SDK posts the identical request one more time under the same message identifier before it throws. When the error still reaches your code, `isOutgoingMessageError(error)` gives you `error.clientMessageId`. Call `send()` again with that identifier and the SDK replays the stored ciphertext. Never send the same content under a new identifier, and never change the request under a reused one: the Relay answers 409 `RETRY_CONFLICT`, which is terminal. See the [Relay delivery table](https://docs.open-e2ee.dev/reference/errors.md#relay-delivery).

**Explicitly non-retryable.** The SDK treats ten codes as terminal and will not retry them. Eight are `EncryptionErrorCode` values: `INVALID_PREKEY_BUNDLE`, `ENCRYPTION_FAILED`, `TOO_MANY_SKIPPED_MESSAGES`, `KEY_STORAGE_ERROR`, `UNTRUSTED_IDENTITY`, `SIGNATURE_VERIFICATION_FAILED`, `RECIPIENT_NOT_REGISTERED`, and `PREKEY_FETCH_RATE_LIMITED`. Two are the Relay codes `UPGRADE_REQUIRED` and `DEVICE_REVOKED`. `HostedSignalProtocolRelayUpgradeRequiredError` carries `UPGRADE_REQUIRED` when the Relay no longer serves the protocol version of the SDK. Only a newer SDK release succeeds. See [Relay protocol version](https://docs.open-e2ee.dev/reference/errors.md#relay-protocol-version).

The SDK also does not retry `HostedSignalProtocolRelayDeviceUnknownError`. See [when the Relay refuses this device](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-relay-refuses-this-device).

**Never wrap a decrypt in a retry.** This is the single most common mistake. Retrying `decryptMessage(...)` does not help. The applicable message key was already consumed or was never derivable. Each attempt re-enters a state machine that moves forward.

Repeated attempts against a damaged session consume the skipped-key budget. They can leave ratchet state less recoverable than before. If a decrypt fails, route to recovery. Do not try again.

**Never retry an identity change.** `UNTRUSTED_IDENTITY` means the candidate no
longer matches the peer's pinned tuple. That is a trust decision belonging to a
person. Automating it converts a security control into a notification.

> **Tradeoff — Fail closed vs. keep the conversation moving**
>
> Failing closed on an identity change is correct. It also loses messages and creates support tickets because most identity changes come from reinstallations. Auto-accepting keeps the thread active and removes the user's signal that something changed. The SDK cannot select a default. The correct choice depends on whether your users reinstall frequently or manage a small set of high-risk accounts. Select one choice and describe it accurately in the UI.

## When the Relay refuses this device [#when-the-relay-refuses-this-device]

The Relay can refuse this device. Two errors name that refusal. Neither is an `EncryptionError`, and the SDK retries neither one. The main entry and `/client` export both classes.

| Error | Cause | What the application does |
|---|---|---|
| `HostedSignalProtocolRelayDeviceRevokedError` | An account recovery revoked this device, or the device was removed from the account, for example by [idle expiry](https://docs.open-e2ee.dev/signal-relay/device-lifecycle-and-recovery.md#remove-idle-linked-devices). `code` is `DEVICE_REVOKED`, `status` is 403, and `retryable` is false. | Sign the user out of this device. A removal or an idle expiry revokes the device's authentication key permanently. The Relay refuses that key with `DEVICE_REVOKED` on a token refresh, a registration, and a device link. To use this device again, [link it](https://docs.open-e2ee.dev/signal-relay/device-lifecycle-and-recovery.md#link-and-revoke-devices) again from the primary device. The new link gets a new device key. |
| `HostedSignalProtocolRelayDeviceUnknownError` | A device token request found no device for the stored session. `code` is `NOT_FOUND`, `status` is 404, and `retryable` is false. | Ask the user to confirm a re-registration of this device. Do not re-register without that confirmation. When the account has other devices, the Relay refuses the re-registration with `DEVICE_LINK_REQUIRED`. See [When the account already has a device](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-account-already-has-a-device). |

The SDK never registers a device or retries after a device refusal. `createHostedSignalProtocolClient` throws either error when the stored session cannot get a device token. It does not register a new device in its place. A running client throws them from its Relay calls. A client call can wrap them in an `EncryptionError`, as the `originalError`. `isRetryableError()` returns false for both errors.

The mailbox subscription stops with the reason `device-revoked` or `device-unknown`. It does not reconnect and does not pull. A `switch` over `SignalProtocolRelayConnectionReason` must handle both values.

The subscription also stops with the reason `authority-refused` when the Relay refuses its socket token request or a pull conclusively. That refusal has `retryable` false and the code `AUTHORITY_DENIED`, `NOT_FOUND`, or `OPERATION_EXPIRED`. A deleted account gets this refusal. A refusal with `retryable` true goes to the retry schedule. A `NOT_FOUND` on the socket token request is a refusal of this device, so the reason is then `device-unknown`.

### Re-register a device [#re-register-a-device]

To re-register, create the client again with `assertionPurpose: 'reregister'`. The client keeps the stored identity and device key, and it asks for a `register` assertion. It throws before any assertion when the store holds no identity or no device key. A retry after a failed call sends the same registration again.

A re-registration has these effects:

- When the account holds this device key with the same Signal identity, the device keeps its device ID.
- When the account holds other devices but not this device key, the Relay refuses the re-registration with `DEVICE_LINK_REQUIRED`. If recovery revoked the device and the Relay has no revoked-key record, the device reads as unknown. It gets this refusal. See [When the account already has a device](https://docs.open-e2ee.dev/operate/error-handling.md#when-the-account-already-has-a-device).
- After the SDK submits an account deletion request from this store, it refuses the re-registration with `DELETION_ALREADY_REQUESTED`. To register the person again with a new account, see [Register after account deletion](https://docs.open-e2ee.dev/signal-relay/limits-billing-and-operations.md#register-after-account-deletion).
- When a deletion removed the account, the Relay refuses the re-registration with `AUTHORITY_DENIED`. The Relay refuses each registration with an identity of a deleted account, for example a store copy that holds the device-owned identity key of the deleted account.

```ts
import {
  HostedSignalProtocolRelayDeviceRevokedError,
  HostedSignalProtocolRelayDeviceUnknownError,
  createHostedSignalProtocolClient,
} from '@open-e2ee/signal-protocol-sdk';

try {
  signal = await createHostedSignalProtocolClient(options);
} catch (error) {
  if (error instanceof HostedSignalProtocolRelayDeviceRevokedError) {
    signOutThisDevice();
  } else if (
    error instanceof HostedSignalProtocolRelayDeviceUnknownError &&
    (await confirmReregistration())
  ) {
    signal = await createHostedSignalProtocolClient({
      ...options,
      hosted: { ...options.hosted, assertionPurpose: 'reregister' },
    });
  } else {
    throw error;
  }
}
```

### When the account already has a device [#when-the-account-already-has-a-device]

The Relay registers only the first device of an account. A registration with a new device key on an account that has a device gets HTTP 409. `createHostedSignalProtocolClient` then throws a `HostedSignalProtocolRelayHttpError` with `code` `DEVICE_LINK_REQUIRED`, `status` 409, and `retryable` false. This occurs with custom-token and native provider identity. Examples are a reinstall, a new phone, and cleared site data.

Do not retry the registration. A retry sends the same registration and gets the same refusal. Do not wrap the registration in `withRetry()`: `isRetryableError()` returns `true` for this error, because the check does not read `retryable` and does not list `DEVICE_LINK_REQUIRED`. Do one of these:

- Link the device from an active device of the account. See [Multi-device](https://docs.open-e2ee.dev/build/multi-device.md).
- Recover the account with `assertionPurpose: 'recover'`. Recovery revokes every earlier device of the account.

A known device key with a different Signal identity gets `KEY_PROOF_INVALID`. In device-owned identity, a new store makes a new account, so it does not get this refusal.

## When a retry request ends with no resend [#when-a-retry-request-ends-with-no-resend]

A failed decrypt asks the sender device for a resend. That retry request can end with no resend. The content of the failed envelope is then lost. The `onRetryTerminal` hook tells your application when this happens, so it can show that the message is unavailable.

The hook runs once for each request, with a `RetryTerminalEvent`. The event has the terminal `class`, the `failedEnvelopeId`, and `recovery?`. Only a `posting-deadline` end resets the session. A `request-expired` end that the SDK moved from an SDK 13.x record can also have `recovery`. The `failedEnvelopeId` is the Relay message ID of the envelope that the requester failed to decrypt. The main entry and `/client` export the `RetryTerminalEvent` and `RetryTerminalClass` types.

| Class | Cause | Device that gets it |
|---|---|---|
| `missing-sender` | The device that sent the failed message is gone. | The requester |
| `revoked-authority` | The Relay revoked the authority of the post. | The requester |
| `request-expired` | The Relay answered or holds the latest attempt of the request, and the content did not come before the deadline. The deadline is 14 days after the first failure. The session does not reset. This class is not the delivery error cause `request-ended`. | The requester |
| `posting-deadline` | The Relay did not accept the latest attempt of the request. A post was due at or after the posting deadline, 24 hours after the first failure, or the Relay refused a post with `OPERATION_EXPIRED`, or the request got to its deadline. The requester then archives its session with the sender device, and `recovery` describes that reset. | The requester |
| `attempts-exhausted` | The resend that answers the fifth attempt also failed. The request posts no sixth attempt and resets no session. | The requester |
| `deletion` | The account of the other device is deleted. | The requester |
| `abuse-allowance-exhausted` | The sender used up its retry allowance. | The requester |
| `missing-prekey` | The Relay has no prekey bundle of the requester, so the sender of the resend cannot start a new session. | The sender of the failed message |
| `membership-refused` | The requester is not a current member of the group of the message, or the group has no membership source, so the sender gives no content. | The sender of the failed message |

```ts
signal.registerHook('onRetryTerminal', async (event) => {
  await messageStore.markUndecryptable(event.failedEnvelopeId, event.class);
});
```

The SDK stores the terminal state before it calls the hook. A client stop during the hook can make it run again after the next start. Write the hook so that a second call for the same `failedEnvelopeId` has no new effect.

## Session recovery [#session-recovery]

Four operations, in ascending order of destruction:

- `hasSession(remoteAddress)`: cheap existence check before you decide anything.
- `getSessionHealth(userId)`: diagnostics. Returns `status`, `sessionExists`, `issues[]`, a `keyStatus` block (`hasIdentityKey`, `hasSignedPreKey`, `hasKyberPreKey`, `signedPreKeyAgeDays`, `kyberPreKeyAgeDays`, `needsRotation`), and, when a session exists, `sessionStatus` with `ageDays`, `messagesSent`, `messagesReceived`, `isExpiredForSending`, and `isExpiredForReceiving`.
- `archiveSession(remoteAddress)`: moves the current session to the inactive list. This preserves it for delayed message decryption. Per SESAME §3.2 the "previously active session is moved to the head of the inactive sessions list." Use this operation when a peer reinstalls and their session no longer matches. Messages encrypted to the old session can still arrive.
- `deleteSession(remoteAddress)`: destroys it. Anything still in flight under that session becomes undecryptable.

`forceCompleteKeyReset()` sits outside this ladder. It returns a `ForceKeyResetResult` counting `deletedSessions` and `deletedPreKeys`, and the SDK documents it as a development and debugging operation. If production code calls it, the product lacks a recovery path. The call is not itself a recovery path.

**Opacity ledger**

| Artifact | Stays on device | Sent to relay | In object store | Visible as metadata |
|---|---|---|---|---|
| `EncryptionError.code` | yes | no | no | safe to export to telemetry |
| `EncryptionError.context` | yes | no | no | export only after redaction |
| `.identity` | yes | no | no | public halves; never log |
| `.untrustedAddress` | yes | no | no | identifies a peer; treat as PII |
| Failed ciphertext | yes | already at relay | no | envelope size |
| Message plaintext | yes | no | no | no |
| Session record (`version: 4`) | yes | no | no | no |

> **Not covered — Undecryptable-message triage across two devices**
>
> To diagnose one failed message for one recipient, correlate evidence from both sides. [Observability](https://docs.open-e2ee.dev/operate/observability.md) covers that workflow and its limits.

## Request registration support [#request-registration-support]

If a registration response provides `x-signal-relay-request-id`, copy only its value.
SDK 14.4 does not add that reference to its error object.
In a browser, open developer tools and select the registration request in the Network panel.
Read the ID from the response headers.
For SDK versions that provide an optional `error.requestId`, use it when present.
An absent ID does not establish whether a request occurred.

Send the request ID, approximate UTC time, SDK version, and runtime name and version.
Include the public HTTP status and error code when available.
State the environment, Sandbox or Production, the operation, and whether this was the first attempt or a retry.
The ID grants no diagnostic read access.
A missing retained record leaves the historical outcome unknown.

Do not send HAR files, cURL output, tokens, assertions, private keys, or database contents.
Keep the encrypted device store and existing identity.
Do not clear storage, reinstall, or reset the identity to get a request ID.

## Next [#next]

- [Observability without plaintext](https://docs.open-e2ee.dev/operate/observability.md)
- [Testing encrypted flows](https://docs.open-e2ee.dev/operate/testing.md)
- [Identity change and safety numbers](https://docs.open-e2ee.dev/build/identity-change-safety-numbers.md)
- [Errors reference](https://docs.open-e2ee.dev/reference/errors.md)
