Mem0 on Kubernetes in Practice: v2.2.1 Three-Tier Architecture, V3 Memory Pipeline, and Multi-Replica Pitfalls¶
Overview and Background¶
In long-running AI agent architectures, relying solely on context-window stuffing or static document RAG breaks down when managing cross-session user preferences, role changes, and ephemeral incident records: conversations outgrow context limits, preference changes create conflicting facts, and separate agent frameworks end up siloed with disconnected state.
Mem0 (mem0ai/mem0) is one of the most active open-source standalone memory layers (Apache-2.0, nearly 70k stars). Many existing deployment guides still describe the old single-file main.py paired with the archived ankane/pgvector:v0.5.1 image. By v2.2.1, however, the official self-hosted server has evolved into a secure-by-default three-tier stack—PostgreSQL 17 + pgvector 0.8.7 + FastAPI Server + Next.js 15 Dashboard—powered by a new V3 single-LLM-call extraction pipeline.
This guide deploys the complete Mem0 v2.2.1 stack on Kubernetes v1.37.2 (containerd://2.4.2, multi-node linux/amd64 cluster with local LVM persistent volumes), backed by an OpenAI-compatible LLM gateway and an in-cluster 100% offline BAAI/bge-small-zh-v1.5 (512-dim ONNX CPU) embedding microservice. We benchmark authentication, fact extraction and temporal transitions, multi-tenant isolation, Pod deletion recovery, and multi-replica consistency—documenting five real engineering pitfalls verified against live cluster traffic and source code.
One-Sentence Conclusion¶
The official Mem0 v2.2.1 three-tier stack runs cleanly on Kubernetes in roughly 488 MiB of core resident memory (730 MiB including a local offline embedder), providing a ready-to-use cross-agent memory service with a web audit dashboard—yet its default architecture remains single-writer rather than horizontally stateless: mutation history and the rolling 10-message session window still live in local SQLite (/app/history/history.db), POST /configure hot-reloads only the Pod that handled the request, and X-API-Key authentication executes synchronous bcrypt verification on every request, adding 465–500 ms of pure CPU overhead (the exact same search takes 99 ms with Bearer JWT versus 598 ms with X-API-Key).
Key Findings¶
- Architecture and version shift:
v2.2.1replaces the archivedankane/pgvectorimage with officialpgvector/pgvector:pg17(shippingpgvector 0.8.7) and splits persistence across two PostgreSQL databases—postgresfor vectors plus HNSW + GIN hybrid indexes, andmem0_appmanaged by Alembic migrations (001through006) for users, single-use refresh tokens, runtime overrides, and a BRIN-indexedrequest_logsaudit table. - V3 additive temporal extraction pipeline: instead of making two sequential LLM calls on every write, Mem0 loads the last
10session messages from local SQLite, retrievestop_k=10existing memories, and issues a single LLM call that emits time-anchored additive facts (3.64 sfor initialADDof5facts,5.84 sfor temporal transition updates,2.97 sreturning an empty list on duplicate inputs). - Biggest hidden performance bottleneck:
server/auth.pyhashes high-entropy48-characterm0sk_API keys usingbcryptand runspwd_context.verify()synchronously on every request. Five-run medians showGET /configurejumping from16 ms(JWT) to481 ms(X-API-Key,30× slower), andPOST /searchjumping from99 ms(JWT) to598 ms(X-API-Key,6× slower). - Two empirically proven multi-replica split-brain hazards: spinning up a
2ndmem0-apiPod against the same Postgres caused Pod 1 to return2ADD -> UPDATEhistory events while Pod 2 returned0; updatingcustom_instructionsviaPOST /configureon Pod 1 left Pod 2 serving stale in-memory configuration indefinitely. - Resilient stateful recovery: with RWO PVCs attached, deleting
mem0-apirecovered to Ready in14.98 sand served its first authenticated call at16.76 s(preserving the512-dim override, all10memories, and2SQLite history rows); deletingpostgres-0recovered to Ready in8.09 sand auto-reconnected vector search at10.49 s.
Architecture Positioning and Version Evolution¶
Before deploying Mem0 into Kubernetes, it is essential to map the actual runtime topology and persistence boundaries of Mem0 v2.2.1 rather than assuming a purely stateless API backed solely by PostgreSQL.

Figure 1: Three-tier topology, air-gapped local embedder integration, and dual persistence boundaries of Mem0 v2.2.1 on Kubernetes.
Open-Source Self-Hosted vs. Hosted Cloud Boundaries¶
Cross-checking upstream source code against our live Next.js 15 Dashboard (whose sidebar explicitly marks hosted features with PRO badges) clarifies the exact boundary:
| Component / Capability | Self-Hosted Status | Observed Kubernetes Behavior |
|---|---|---|
FastAPI core API (/memories, /search, /configure) |
Apache-2.0 open source | Auth enabled by default (401 unauthenticated); single Pod idles at 241.6 MiB |
PostgreSQL 17 + pgvector 0.8.7 |
Default open-source vector & metadata store | Auto-creates vector(N), hnsw cosine index, and gin lemmatized full-text index |
| Next.js 15 Web Dashboard | Bundled open source | Exposes Requests, Memories, Entities, API Keys, Configuration, Settings in 89.0 MiB |
Categories / Webhooks / Analytics / Export |
Cloud Pro hosted tier only | Shown with PRO badges in the sidebar; unavailable in self-hosted mode |
| Graph Memory (Neo4j / Memgraph / Kuzu) | Optional open-source extension | Drivers are not bundled in server/requirements.txt; requires separate graph DB and custom image |
Mutation history and last 10 session turns |
Embedded local SQLite | Writes to /app/history/history.db, enforcing a single-writer constraint on mem0-api |
Comparison with Other Agent Memory Approaches¶
| Dimension | Mem0 v2.2.1 Self-Hosted | Plain pgvector / Qdrant RAG | Zep / Graphiti | Framework Store (LangGraph Store) |
|---|---|---|---|---|
| Core capability | Automatic LLM fact extraction, deduplication, temporal updates, multi-scope filtering | Chunked document retrieval without automatic fact merging | Strong temporal knowledge graphs and entity-relation evolution | Framework-scoped checkpoints and key-value state |
| Infrastructure footprint | Low (starts with one PostgreSQL 17 plus optional local embedder) | Minimal (vector store only) | Medium-high (graph DB + dedicated extraction pipeline) | Low (deployed alongside orchestrator) |
| Built-in admin UI | Includes Next.js 15 Dashboard and request audit log | None | Enterprise console or custom UI | Requires external platform UI |
| Multi-replica scaling | Constrained by local SQLite and in-memory config (single-writer unless modified) | Natively stateless | Depends on backend graph store and shared state | Depends on storage backend |
Production Container Images and Kubernetes Manifests¶
Upstream server/Dockerfile still ships development defaults (uvicorn ... --reload, running as root, no automatic alembic upgrade head), which risks reload glitches, unmigrated tables, and overly broad privileges in clusters. Production rollout calls for two clean images and a hardened manifest.
Hardened Mem0 Server and Air-Gapped Embedder Images¶
The server image installs v2.2.1 directly from source, drops --reload, and runs as non-root UID 1000:
FROM python:3.12-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
&& rm -rf /var/lib/apt/lists/*
COPY server/requirements.txt /tmp/server-requirements.txt
RUN pip install --no-cache-dir -r /tmp/server-requirements.txt
COPY pyproject.toml README.md /tmp/mem0-pkg/
COPY mem0 /tmp/mem0-pkg/mem0
RUN pip install --no-cache-dir --no-deps /tmp/mem0-pkg \
&& rm -rf /tmp/mem0-pkg /tmp/server-requirements.txt
COPY server /app
RUN groupadd -g 1000 mem0 \
&& useradd -m -u 1000 -g 1000 -s /bin/bash mem0 \
&& mkdir -p /app/history \
&& chown -R mem0:mem0 /app
USER mem0
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
HISTORY_DB_PATH=/app/history/history.db
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
In many enterprise intranets, internal LLM gateways expose /v1/chat/completions without /v1/embeddings. We packaged a lightweight OpenAI-compatible embedding service using fastembed (ONNX CPU), baking BAAI/bge-small-zh-v1.5 (512-dim) into /models at build time so it runs 100% air-gapped in 241.9 MiB of RAM:
FROM python:3.12-slim
WORKDIR /app
RUN pip install --no-cache-dir fastapi==0.115.8 uvicorn==0.34.0 fastembed==0.7.3
ENV FASTEMBED_CACHE_PATH=/models \
EMBED_MODEL=BAAI/bge-small-zh-v1.5 \
PYTHONUNBUFFERED=1
RUN python3 -c "from fastembed import TextEmbedding; m = TextEmbedding('BAAI/bge-small-zh-v1.5', cache_dir='/models'); v = next(m.embed(['init'])); print('baked dim =', len(v))"
COPY app.py /app/app.py
RUN groupadd -g 1000 embedder \
&& useradd -m -u 1000 -g 1000 -s /bin/bash embedder \
&& chown -R embedder:embedder /app /models
USER embedder
EXPOSE 8080
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]
Complete Three-Tier Kubernetes Manifest¶
Below is the sanitized manifest validated end to end in namespace mem0-lab, covering StatefulSet/postgres, Deployment/mem0-embedder, Deployment/mem0-api (with init-history-dir and alembic upgrade head initContainers), and Deployment/mem0-dashboard:
apiVersion: v1
kind: Namespace
metadata:
name: mem0-lab
---
apiVersion: v1
kind: Secret
metadata:
name: mem0-secrets
namespace: mem0-lab
type: Opaque
stringData:
POSTGRES_PASSWORD: "<replace-with-strong-password>"
JWT_SECRET: "<replace-with-openssl-rand-base64-48>"
OPENAI_API_KEY: "<replace-with-llm-gateway-token>"
---
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-init-db
namespace: mem0-lab
data:
init-db.sh: |
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
SELECT 'CREATE DATABASE mem0_app'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mem0_app')\gexec
EOSQL
---
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: mem0-lab
spec:
selector:
app: postgres
ports:
- name: pg
port: 5432
targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: mem0-lab
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: pgvector/pgvector:pg17
ports:
- containerPort: 5432
env:
- name: POSTGRES_USER
value: postgres
- name: POSTGRES_DB
value: postgres
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: mem0-secrets
key: POSTGRES_PASSWORD
readinessProbe:
exec:
command: ["sh", "-c", "pg_isready -q -d postgres -U postgres"]
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
exec:
command: ["sh", "-c", "pg_isready -q -d postgres -U postgres"]
initialDelaySeconds: 15
periodSeconds: 10
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: "2"
memory: 4Gi
volumeMounts:
- name: pg-data
mountPath: /var/lib/postgresql/data
- name: init-db
mountPath: /docker-entrypoint-initdb.d/init-db.sh
subPath: init-db.sh
volumes:
- name: init-db
configMap:
name: postgres-init-db
defaultMode: 0755
volumeClaimTemplates:
- metadata:
name: pg-data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: local-lvm
resources:
requests:
storage: 10Gi
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mem0-history
namespace: mem0-lab
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: local-lvm
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
name: mem0-api
namespace: mem0-lab
spec:
selector:
app: mem0-api
ports:
- name: http
port: 8000
targetPort: 8000
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: mem0-api
namespace: mem0-lab
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: mem0-api
template:
metadata:
labels:
app: mem0-api
spec:
securityContext:
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
fsGroupChangePolicy: OnRootMismatch
initContainers:
- name: init-history-dir
image: ghcr.io/example/mem0-server:v2.2.1
securityContext:
runAsUser: 0
runAsGroup: 0
command: ["sh", "-ec", "mkdir -p /app/history && chown -R 1000:1000 /app/history"]
volumeMounts:
- name: history-data
mountPath: /app/history
- name: db-migrate
image: ghcr.io/example/mem0-server:v2.2.1
command:
- sh
- -ec
- |
python3 -c "import os, time, psycopg
for _ in range(60):
try:
with psycopg.connect(host=os.environ['POSTGRES_HOST'], port=os.environ['POSTGRES_PORT'], user=os.environ['POSTGRES_USER'], password=os.environ['POSTGRES_PASSWORD'], dbname=os.environ['APP_DB_NAME']):
break
except Exception:
time.sleep(2)
else:
raise SystemExit('Postgres not ready')"
alembic upgrade head
env:
- name: POSTGRES_HOST
value: postgres.mem0-lab.svc.cluster.local
- name: POSTGRES_PORT
value: "5432"
- name: POSTGRES_USER
value: postgres
- name: POSTGRES_DB
value: postgres
- name: APP_DB_NAME
value: mem0_app
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: mem0-secrets
key: POSTGRES_PASSWORD
containers:
- name: mem0-api
image: ghcr.io/example/mem0-server:v2.2.1
ports:
- containerPort: 8000
env:
- name: POSTGRES_HOST
value: postgres.mem0-lab.svc.cluster.local
- name: POSTGRES_PORT
value: "5432"
- name: POSTGRES_DB
value: postgres
- name: POSTGRES_USER
value: postgres
- name: POSTGRES_COLLECTION_NAME
value: memories
- name: APP_DB_NAME
value: mem0_app
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: mem0-secrets
key: POSTGRES_PASSWORD
- name: JWT_SECRET
valueFrom:
secretKeyRef:
name: mem0-secrets
key: JWT_SECRET
- name: OPENAI_API_KEY
valueFrom:
secretKeyRef:
name: mem0-secrets
key: OPENAI_API_KEY
- name: OPENAI_BASE_URL
value: http://llm-gateway.mem0-lab.svc.cluster.local:8181/v1
- name: MEM0_DEFAULT_LLM_MODEL
value: deepseek-v4-flash
- name: MEM0_DEFAULT_EMBEDDER_MODEL
value: BAAI/bge-small-zh-v1.5
- name: AUTH_DISABLED
value: "false"
- name: MEM0_TELEMETRY
value: "false"
- name: DASHBOARD_URL
value: http://127.0.0.1:13000
- name: HISTORY_DB_PATH
value: /app/history/history.db
readinessProbe:
httpGet:
path: /openapi.json
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
httpGet:
path: /openapi.json
port: 8000
initialDelaySeconds: 15
periodSeconds: 15
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: "2"
memory: 2Gi
securityContext:
allowPrivilegeEscalation: false
volumeMounts:
- name: history-data
mountPath: /app/history
volumes:
- name: history-data
persistentVolumeClaim:
claimName: mem0-history
---
apiVersion: v1
kind: Service
metadata:
name: mem0-dashboard
namespace: mem0-lab
spec:
selector:
app: mem0-dashboard
ports:
- name: http
port: 3000
targetPort: 3000
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: mem0-dashboard
namespace: mem0-lab
spec:
replicas: 1
selector:
matchLabels:
app: mem0-dashboard
template:
metadata:
labels:
app: mem0-dashboard
spec:
containers:
- name: mem0-dashboard
image: ghcr.io/example/mem0-dashboard:v2.2.1
ports:
- containerPort: 3000
env:
- name: API_INTERNAL_URL
value: http://mem0-api.mem0-lab.svc.cluster.local:8000
- name: NEXT_PUBLIC_API_URL
value: http://127.0.0.1:18888
- name: NEXT_PUBLIC_INSTANCE_NAME
value: Mem0-K8s-Lab
readinessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 15
periodSeconds: 15
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: "1"
memory: 1Gi
securityContext:
allowPrivilegeEscalation: false
Four Kubernetes-specific details deserve explicit care:
strategy.type: Recreate: becausemem0-apimounts the RWOmem0-historyPVC, defaultRollingUpdatewill deadlock onMulti-Attachwhen old and new Pods contend for the volume.PGDATA=/var/lib/postgresql/data/pgdata: avoids PostgreSQL init failures caused bylost+foundat the root of local LVM filesystems.- Probe
/openapi.json:mem0-apiexposes no/api/health, whereas/openapi.jsonsits explicitly inSKIPPED_REQUEST_LOG_PATHSso probes never polluterequest_logs. MEM0_TELEMETRY=false: disables default PostHog onboarding telemetry for air-gapped environments.
End-to-End Verification and Performance Anatomy¶
Once all Pods became Ready, we executed all requests from a separate client Pod across nodes through ClusterIP Service mem0-api.mem0-lab.svc.cluster.local:8000. Raw sanitized telemetry is stored in results.json.

Figure 2: Five-run median auth latency comparison, Pod resident memory footprint, recovery timings, and V3 single-call write latency for Mem0 v2.2.1 on Kubernetes.
Auth Bootstrap and Security Baseline¶
- An unauthenticated
GET /memoriesimmediately returned401 Unauthorized, confirming secure-by-default enforcement. - After registering the initial admin via
POST /auth/register, Alembic migration004's partial unique index locked registration; a second attempt returned403 {"detail":"Registration is closed. An admin account already exists."}. - Creating an API key via
POST /api-keysissued a48-characterm0sk_key, andGET /configuremasked bothpasswordandapi_keyas"[redacted]".
V3 Single-Call Extraction, Temporal Evolution, and Deduplication¶
With 512-dim pgvector and custom instructions configured, we ran three sequential turns for user alice to observe the v2.2.1 V3 additive pipeline in action:
- Turn 1 (initial profile
ADD,3639 ms): given a Chinese message describing city, team, tech stack, severe peanut allergy, and black coffee habit, Mem0 extracted5clean atomic facts in one LLM call (allevent: "ADD"). - Turn 2 (temporal state transition,
5842 ms): given a role transfer to Shanghai's AI inference platform team (vLLM/SGLang) and switching from black coffee to oat lattes,v2.2.1preserved prior facts and added time-stamped transition memories such asUser switched from drinking black coffee in the mornings to oat lattes around December 2026, while keeping the severe peanut allergy untouched. - Turn 3 (duplicate input deduplication,
2969 ms): repeating the peanut allergy and Go controller facts returned{"results": []}with zero duplicate vector rows. - Explicit in-place mutation trail: calling
PUT /memories/{id}updated a memory in place, andGET /memories/{id}/historyreturned2audit entries (ADD->UPDATE) recording exactold_memoryandnew_memorysnapshots.
Multi-Tenant Isolation, Cross-Lingual Retrieval, and Live Dashboard Evidence¶
We populated distinct scopes—user_id: "bob" (4 memories), agent_id: "k8s-copilot" (1 cluster runbook), and run_id: "incident-2026-1203" (2 incident memories with expiration_date: "2026-12-31")—yielding 15 vector(512) rows visible in the live Next.js 15 Dashboard:

Figure 3: Live light-mode screenshot of the Mem0 v2.2.1 Dashboard (Memories view) running on Kubernetes, showing multi-tenant extracted facts alongside the sidebar PRO cloud boundary.
Two retrieval observations stood out:
- Strict tenant isolation: querying
"alice 对什么过敏?"insideuser_id: "bob"returned onlybob's own memories with zero cross-tenant leakage. - Cross-lingual score drop when English facts meet Chinese queries: an English query (
"Which GPU incident happened on node-02?") matched with cosine similarity0.771, whereas a Chinese query ("alice现在在哪个城市做什么方向?") scored only0.356onbge-small-zh-v1.5. Because Mem0 defaults to extracting facts in English even from Chinese conversations, lightweight Chinese-first embedders suffer a cross-lingual score penalty. Chinese production workloads should either require Simplified Chinese output insidecustom_instructionsor adopt a strong multilingual embedder such asBAAI/bge-m3(1024-dim).
Unexpected Bottleneck: Per-Request bcrypt Adds 6x Search Latency¶
Inspecting the Dashboard's Requests audit table revealed a striking anomaly: even GET /configure—an in-memory dictionary read touching no vector store—took 464–475 ms!

Figure 4: Live Requests audit log view showing total_logs: 29, probe_logs: 0, ~465 ms GET /configure latency, and automatic pool recovery from 502 to 200 after postgres-0 restarted.
Reading server/auth.py revealed the root cause: generate_api_key() and verify_api_key_hash() apply password-grade bcrypt to high-entropy 48-character random API keys (m0sk_...) and run verification synchronously on every request without caching, burning 460–500 ms of CPU per API call. Our 5-run A/B benchmark confirmed the impact:
| Endpoint | X-API-Key (5 raw runs / median) |
Bearer JWT (5 raw runs / median) |
Speedup |
|---|---|---|---|
GET /configure |
648 / 482 / 480 / 480 / 481 ms (481 ms) |
17 / 16 / 16 / 15 / 16 ms (16 ms) |
JWT 30× faster |
POST /search |
510 / 545 / 600 / 598 / 695 ms (598 ms) |
103 / 99 / 98 / 100 / 99 ms (99 ms) |
JWT 6× faster |
Without patching auth.py, a single Uvicorn worker caps out around 2 req/s under X-API-Key traffic, with over 83% of search latency spent in synchronous bcrypt hashing. High-throughput internal callers should either authenticate with short-lived Bearer JWT tokens or patch API key hashing to salted SHA-256 / HMAC (cryptographically sound for 256-bit random keys at < 0.1 ms).
Pod Deletion and Stateful Recovery¶
We tested kubectl delete pod against both mem0-api and postgres-0:
| Target | Delete Command | Pod Ready | First Verified Request | State Integrity |
|---|---|---|---|---|
mem0-api |
1.874 s |
14.981 s |
16.763 s |
512-dim config reloaded from mem0_app.settings; 10 alice memories and 2 SQLite history rows intact |
postgres-0 |
0.919 s |
8.085 s |
10.494 s |
Attempt 1 hit a stale pool connection (502); attempt 2 (1 s later) auto-reconnected with all 15 vectors intact |
Five Real Kubernetes Pitfalls and Security Hardening¶
Default pgvector 1536 Dimensions Causes Misleading 502 Errors¶
Symptom: pointing stock v2.2.1 at our 512-dim BAAI/bge-small-zh-v1.5 embedder caused the first POST /memories to return a misleading HTTP 502 {"detail":"Upstream provider error."}.
Root cause: DEFAULT_CONFIG in server/main.py omits embedding_model_dims, causing PGVector to default to 1536 dimensions (vector(1536)). Inserting a 512-dim embedding raises psycopg.errors.DataException: expected 1536 dimensions, not 512, which FastAPI's generic exception handler wraps into 502 Upstream provider error.
Fix: before inserting data (or after dropping the empty table), call admin POST /configure with both vector_store.config.embedding_model_dims: 512 and embedder.config.embedding_dims: 512; overrides persist in mem0_app.settings across restarts.
Multi-Replica SQLite Split-Brain and Config Drift¶
Empirical proof: launching a temporary 2nd Pod (mem0-api-replica2) against the same postgres-0 demonstrated both hazards directly:
- History and context split-brain: querying
/memories/{id}/historyfor the same updated memory returned2events on Pod 1 but0events on Pod 2. BecauseSQLiteManager'smessagestable also holds the rolling10-message context window used in V3 Phase 0, running multiple replicas fragments cross-turn coreference resolution. - Hot-reload config drift: posting
custom_instructions: "REPLICA-DRIFT-MARKER-V2"to Pod 1 updated Pod 1 immediately while Pod 2 continued serving the old instructions—server_state.pyrefreshes only the local process's_memory_instancewith no cross-Pod notification.
Fix: with the stock server image, stick to replicas: 1 + strategy.type: Recreate + RWO PVC on /app/history. True multi-replica HA requires moving SQLiteManager tables into PostgreSQL and adding version polling or PostgreSQL LISTEN/NOTIFY to server_state.py.
Probe Noise in request_logs and Scheduled Pruning¶
mem0_app.request_logs is append-only (upstream estimates ~864k rows/day at 10 req/s). Pointing a readinessProbe at /auth/setup-status floods the audit table with tens of thousands of junk entries daily. Probing /openapi.json yielded probe_logs = 0, and production clusters should schedule a Kubernetes CronJob running python3 scripts/prune_request_logs.py to leverage the created_at BRIN index.
Admin Email Validation Rejects .local Domains¶
Automated bootstrap with admin@mem0-lab.local failed with 422 Unprocessable Entity because Pydantic EmailStr (email-validator) rejects reserved .local TLDs. Use a valid domain syntax beyond reserved suffixes like .dev/.internal (such as admin@example.com) in init jobs and verify GET /auth/setup-status returns {"needsSetup": false} afterward.
Production Hardening Checklist¶
- Keep
AUTH_DISABLED=falseandMEM0_TELEMETRY=false, injectingJWT_SECRETandPOSTGRES_PASSWORDfrom KMS / External Secrets rather than Git. - Apply Kubernetes
NetworkPolicyso onlymem0-dashboardand authorized agent namespaces reachmem0-apion:8000, and onlymem0-apireachespostgreson:5432. - Schedule
CronJoblogical backups for bothpostgres(vectors) andmem0_app, paired with snapshots of/app/history/history.db.
Production Evolution and Selection Advice¶
For teams adopting Mem0 inside enterprise AI platforms, a two-stage rollout works cleanly:
- Small-to-medium workloads (
< 50 QPSsearch): deploy the single-writermem0-api+StatefulSet/postgres(pgvector 0.8.7) + offlinebge-small-zh-v1.5/bge-m3stack documented here, useBearer JWTto avoidbcryptoverhead, and pin output language insidecustom_instructions. Total core memory stays under1 GiB. - High-availability multi-tenant scale: three surgical patches unlock stateless horizontal scaling on top of Mem0's open-source core—(1) replace API-key checks in
server/auth.pywith salted SHA-256/HMAC + short-lived LRU cache; (2) movehistoryandmessagesfrommem0/memory/storage.pyintomem0_appPostgreSQL; and (3) add PostgreSQLLISTEN/NOTIFYor versioned reload toserver_state.pysoPOST /configurestays consistent across HPA replicas.
Summary¶
Deploying and benchmarking the official Mem0 v2.2.1 three-tier stack alongside an offline ONNX embedder on Kubernetes confirmed a compact footprint (488.0 MiB core RSS), 99 ms median semantic search under Bearer JWT, 3.64 s V3 single-call extraction, and 8–15 s Pod recovery. Just as importantly, hands-on verification surfaced five undocumented operational pitfalls—default 1536-dim table creation causing hidden 502 errors, 6×–30× latency inflation from per-request X-API-Key bcrypt hashing, multi-replica local history.db and config split-brain, cross-lingual retrieval score drops, and probe log pollution. Addressing these five boundaries turns Mem0 into a dependable shared memory tier for production multi-agent systems.