> ## Documentation Index
> Fetch the complete documentation index at: https://docs.remem.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Handle Remem Errors Gracefully in Your Production Agent

> Catch Remem exceptions by type and build resilient agents that degrade gracefully — failures should never crash your agent or break the user experience.

Memory operations are network calls, and network calls can fail. The difference between a brittle agent and a production-ready one is whether it handles those failures gracefully. Remem raises specific, typed exceptions for every failure scenario so you can catch exactly the right error and respond appropriately — whether that means logging and continuing, notifying the user, or halting immediately.

## Exception Hierarchy

Remem exposes five exception classes, each mapping to a specific HTTP status code and failure scenario:

| Exception              | HTTP Code | When It Happens                                                |
| ---------------------- | --------- | -------------------------------------------------------------- |
| `RememError`           | any       | Base class — catches any Remem error not matched by a subclass |
| `AuthenticationError`  | 401       | Invalid, missing, or revoked API key                           |
| `PlanLimitError`       | 402       | Memory limit reached on your current plan                      |
| `MemoryNotFoundError`  | 404       | Memory ID does not exist (already deleted or wrong ID)         |
| `DuplicateMemoryError` | 409       | Near-identical memory (≥95% similarity) already stored         |

## Importing Exception Classes

Import all exception classes at the top of your module:

```python theme={null}
from remem import RememClient
from remem.exceptions import (
    RememError,            # base — catches any Remem error
    AuthenticationError,   # 401 — bad or missing API key
    PlanLimitError,        # 402 — hit memory limit for your plan
    MemoryNotFoundError,   # 404 — memory ID does not exist
    DuplicateMemoryError,  # 409 — near-identical memory already stored
)
```

## Handling Each Exception

### AuthenticationError — 401

Raised when your API key is invalid, missing, or revoked. This is not a transient error — retrying with the same key will always fail.

```python theme={null}
from remem import RememClient
from remem.exceptions import AuthenticationError
import os

client = RememClient(api_key=os.getenv("REMEM_API_KEY"))

try:
    client.remember("something", user_id="u1", agent_id="bot")
except AuthenticationError:
    # Key is wrong or missing
    # Do not retry — fix the key first
    print("Invalid API key. Check your REMEM_API_KEY environment variable.")
    raise SystemExit(1)
```

<Warning>
  Never retry on `AuthenticationError`. The key is wrong — retrying with the same key will always fail. Fix the key and redeploy.
</Warning>

### PlanLimitError — 402

Raised when your account has reached its memory limit for the current plan. You can still read and search memories — only new writes are blocked.

```python theme={null}
from remem.exceptions import PlanLimitError

try:
    client.remember("something", user_id="u1", agent_id="bot")
except PlanLimitError as e:
    print(f"Memory limit reached: {e.detail}")
    print("Upgrade at remem.online/pricing")
```

Handle it gracefully in your agent by skipping the write rather than crashing:

```python theme={null}
try:
    client.remember(user_message, user_id=user_id, agent_id=agent_id)
except PlanLimitError:
    # Continue the conversation — just do not store this message
    pass
```

<Info>
  Your agent can still read and search memories when the limit is hit — only new writes are blocked. Your agent will not go blind; it just stops learning new things until you upgrade.
</Info>

### MemoryNotFoundError — 404

Raised when you try to update or delete a memory ID that does not exist — either because it was already deleted or the ID is wrong.

```python theme={null}
from remem.exceptions import MemoryNotFoundError

try:
    client.update(
        memory_id="non-existent-id",
        user_id="u1",
        agent_id="bot",
        new_content="something",
    )
except MemoryNotFoundError:
    # Memory was already deleted or ID is wrong
    # Safe to ignore in most cases
    pass
```

### DuplicateMemoryError — 409

Raised when you try to store content that is already present at 95% similarity or above. This is Remem protecting your memory store from redundant data — treat it as a no-op.

```python theme={null}
from remem.exceptions import DuplicateMemoryError

try:
    client.remember(
        "User is based in Lagos, Nigeria",
        user_id="u1",
        agent_id="bot",
    )
except DuplicateMemoryError:
    # Already stored — this is safe to ignore
    pass
```

<Info>
  `DuplicateMemoryError` is not a real error in most cases — it means Remem protected your database from storing the same fact twice. Ignore it silently in production.
</Info>

### RememError — Catch-All

`RememError` is the base class for all Remem exceptions. Use it as a fallback to catch unexpected errors — server errors, rate limits, or anything else not matched by a specific subclass.

```python theme={null}
from remem.exceptions import RememError

try:
    client.remember("something", user_id="u1", agent_id="bot")
except RememError as e:
    print(f"Remem API error {e.status_code}: {e.detail}")
```

## Production-Ready Pattern

This is the pattern to use in any production agent. Both helper functions are guaranteed never to raise — your agent continues regardless of what Remem returns.

```python theme={null}
from remem import RememClient
from remem.exceptions import (
    RememError,
    AuthenticationError,
    PlanLimitError,
    MemoryNotFoundError,
    DuplicateMemoryError,
)
import logging
import os

logger = logging.getLogger(__name__)
client = RememClient(api_key=os.getenv("REMEM_API_KEY"))


def safe_remember(content: str, user_id: str, agent_id: str) -> bool:
    """
    Store a memory safely. Returns True if stored, False if skipped.
    Never raises — your agent continues regardless.
    """
    try:
        client.remember(content, user_id=user_id, agent_id=agent_id)
        return True

    except DuplicateMemoryError:
        # Already stored — not an error
        return False

    except PlanLimitError:
        # Hit plan limit — log it, continue without storing
        logger.warning("Memory limit reached for user %s", user_id)
        return False

    except AuthenticationError:
        # Key is wrong — this needs immediate attention
        logger.error("Remem authentication failed — check REMEM_API_KEY")
        return False

    except RememError as e:
        # Unexpected error — log and continue
        logger.error("Remem error %s: %s", e.status_code, e.detail)
        return False


def safe_recall(query: str, user_id: str, agent_id: str) -> list:
    """
    Search memories safely. Returns empty list on any error.
    Never raises — your agent always has something to work with.
    """
    try:
        return client.recall(query, user_id=user_id, agent_id=agent_id)

    except AuthenticationError:
        logger.error("Remem authentication failed — check REMEM_API_KEY")
        return []

    except RememError as e:
        logger.error("Remem recall error %s: %s", e.status_code, e.detail)
        return []
```

## Retry Logic

For transient server errors (5xx), use exponential backoff before giving up. Don't retry on client errors (4xx) — those require a code or configuration fix.

```python theme={null}
import time
from remem.exceptions import RememError


def remember_with_retry(
    content: str,
    user_id: str,
    agent_id: str,
    retries: int = 3,
) -> bool:
    for attempt in range(1, retries + 1):
        try:
            client.remember(content, user_id=user_id, agent_id=agent_id)
            return True
        except RememError as e:
            if e.status_code >= 500 and attempt < retries:
                # Server error — wait and retry
                wait = 2 ** attempt   # 2s, 4s, 8s
                time.sleep(wait)
                continue
            # Not a server error or out of retries
            raise
    return False
```

## Error Reference

| HTTP Code | Exception Class        | Meaning                    | What To Do                     |
| --------- | ---------------------- | -------------------------- | ------------------------------ |
| 401       | `AuthenticationError`  | Invalid or missing API key | Fix the key — do not retry     |
| 402       | `PlanLimitError`       | Memory limit reached       | Upgrade plan or skip storing   |
| 404       | `MemoryNotFoundError`  | Memory ID does not exist   | Safe to ignore                 |
| 409       | `DuplicateMemoryError` | Memory already exists      | Safe to ignore                 |
| 5xx       | `RememError`           | Server error               | Retry with exponential backoff |

## Production Checklist

<Note>
  Run through this checklist before shipping any agent that uses Remem in production.
</Note>

<Check>Wrap every `remember()` call — `DuplicateMemoryError` is common and safe to ignore</Check>
<Check>Handle `PlanLimitError` gracefully — agent should continue without storing, not crash</Check>
<Check>Log `AuthenticationError` immediately — it means your key needs fixing</Check>
<Check>Return an empty list from `recall()` on error — agent degrades gracefully with no context</Check>
<Check>Add retry logic for 5xx errors — transient server issues should not kill your agent</Check>
