Zep (Graphiti) on Kubernetes in Practice: Bi-Temporal Knowledge Graph, Stateless Replicas, and Same-Cluster Comparison with Mem0¶
Overview and Background¶
When engineering teams evaluate long-term memory systems for AI agents, Mem0 and Zep are usually the first two candidates on the table. Yet once you move toward open-source self-hosting on Kubernetes, the first trap is an outdated mental model of the Zep ecosystem: the legacy standalone getzep/zep Community Edition server has been retired. Today, getzep/zep primarily hosts commercial Zep Cloud examples and the zep-ingest utility, whereas the active open-source core engine powering Zep's bi-temporal knowledge graph is Graphiti (getzep/graphiti) (Apache-2.0, over 33k stars).
Unlike Mem0's flat vector-centric memory store, Graphiti parses every incoming message (Episode) into an entity-relationship graph tracked across two time axes—world validity time (valid_at / invalid_at) and system transaction time (created_at / expired_at)—stored directly in Neo4j or FalkorDB. At query time, it fuses vector similarity, BM25 full-text search, and graph traversal via Reciprocal Rank Fusion (RRF) with zero LLM calls.
This guide deploys Graphiti v0.32.1 + Neo4j 5.26.2 on Kubernetes v1.37.2 (containerd://2.4.2, multi-node linux/amd64 cluster with local LVM persistent volumes), sharing the exact same LLM gateway, offline BAAI/bge-small-zh-v1.5 (512-dim) embedding microservice, and alice three-turn state-change dataset from Mem0 on Kubernetes in Practice. We present a same-cluster apples-to-apples benchmark alongside four real Kubernetes and upstream-code pitfalls uncovered during rollout.
One-Sentence Conclusion¶
Self-hosting Zep on Kubernetes means wrapping open-source Graphiti v0.32.1 as a stateless authenticated API with a singleton Neo4j connection pool backed by StatefulSet/neo4j (with enableServiceLinks explicitly disabled): on the exact same cluster and models, Zep / Graphiti incurs far higher write cost than Mem0 (a state-transition Episode triggered 11 LLM calls taking 73.6 s, compared to Mem0 V3's 1 call in 5.8 s), but earns two major architectural advantages—automatic invalid_at timestamping of superseded facts and a 100% stateless API tier (2 cross-node replicas with zero split-brain and 5/5 zero-downtime Pod drains)—while serving hybrid search at 101.7 ms 5-run median with zero LLM calls.
Key Findings¶
- Calibrate the open-source target: self-hosting Zep today means building on
getzep/graphiti(v0.32.1), not pulling retired legacy Zep CE images; both upstreamserver/graph_service/andmcp_server/explicitly declare themselves unauthenticated reference implementations, requiring a thin hardened wrapper before cluster exposure. - Bi-temporal invalidation verified live: running the exact same Chinese three-turn test (
2026-06-01Guangzhou / black coffee / peanut allergy ->2026-12-01Shanghai transfer / oat latte), Graphiti preserved native Chinese wording and automatically stampedinvalid_at = 2026-12-01T09:00:00+00:00on superseded edges (Alice 在广州的平台工程团队工作。andAlice 早上只喝黑咖啡。) while keeping the peanut allergy edge atinvalid_at = null; passingonly_valid=truefilters out invalidated facts immediately. - Clear write-heavy, read-fast trade-off:
alice's 3 Episodes consumed2,11, and5LLM calls taking61.7 s,73.6 s, and87.7 s(entity deduplication, edge contradiction resolution, and node summary updates), making asynchronous durable ingestion mandatory rather than blocking live chat turns; hybrid retrieval (Neo4j vector + Lucene BM25 + graph RRF) makes0LLM calls at101.7 ms5-run median. - True stateless multi-replica HA: because all entities, edges, episodes, and
32indexes live in Neo4j,2graphiti-apireplicas spread across two worker nodes (120.9–125.9 MiBRSS each) returned identical graph state (18edges /14valid /4invalidated), and deleting1replica produced5/5HTTP 200responses with zero downtime. - Classic Kubernetes + Neo4j startup trap: naming a Service
neo4jcauses Kubernetes to injectNEO4J_PORT_7687_TCP_PORTenv vars into Pods; Neo4j 5.x's entrypoint translates everyNEO4J_*env var intoneo4j.confand crashes immediately (CrashLoopBackOff) under strict validation—fixed permanently with one line:enableServiceLinks: false.
Architecture Positioning and Three Upstream Reference-Server Gaps¶
Inspecting upstream graphiti/server/graph_service/ (v0.32.1) before writing Kubernetes manifests exposes three production gaps you will immediately hit if you deploy the stock zepai/graphiti image directly:

Figure 1: Stateless 2-replica API topology, SHA-256 authentication layer, and Neo4j 5.26.2 bi-temporal graph architecture of Zep / Graphiti v0.32.1 on Kubernetes.
Upstream Reference Server Gap (server/graph_service/) |
Source Location and Risk | Production Wrapper Fix in This Guide |
|---|---|---|
| Zero authentication plus destructive endpoints | server/README.md states there is no auth; POST /clear wipes the entire graph unauthenticated |
Add constant-time SHA-256 X-API-Key / Bearer middleware (401 unauthenticated, < 0.1 ms overhead) and omit public /clear |
| Broken custom LLM and embedder gateway wiring | zep_graphiti.py mutates base_url after AsyncOpenAI init, never passes embedding_model_name to embedder, and defaults to OpenAI-only OpenAIClient |
Explicitly construct OpenAIGenericClient(structured_output_mode="json_object") and OpenAIEmbedder(base_url=..., embedding_dim=512) |
| Per-request Neo4j driver churn + volatile memory queue | get_graphiti() opens and closes a new driver per request; ingest.py enqueues that soon-closed driver into an in-memory asyncio.Queue dropped on Pod stop |
Hold a singleton Graphiti pool in FastAPI lifespan; expose synchronous receipted /episodes (backed by external MQ in production) |
Production Container Image and Kubernetes Manifests¶
Hardened Graphiti Server Image¶
Built directly from upstream graphiti-core v0.32.1 as non-root UID 1000, running our lean FastAPI wrapper with singleton connection pooling, OpenAIGenericClient (json_object mode), OpenAIEmbedder, and constant-time SHA-256 auth:
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 graphiti/pyproject.toml graphiti/README.md /tmp/graphiti-pkg/
COPY graphiti/graphiti_core /tmp/graphiti-pkg/graphiti_core
RUN pip install --no-cache-dir \
fastapi==0.115.8 \
uvicorn==0.34.0 \
/tmp/graphiti-pkg \
&& rm -rf /tmp/graphiti-pkg
COPY app/main.py /app/main.py
RUN groupadd -g 1000 graphiti \
&& useradd -m -u 1000 -g 1000 -s /bin/bash graphiti \
&& chown -R graphiti:graphiti /app
USER graphiti
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Core client initialization snippet (wiring OpenAI-compatible gateways, offline 512-dim embeddings, and reusable connection pools):
llm_client = OpenAIGenericClient(
config=LLMConfig(
api_key=os.environ["OPENAI_API_KEY"],
base_url=os.environ.get("OPENAI_BASE_URL"),
model=os.environ.get("LLM_MODEL", "deepseek-v4-flash"),
small_model=os.environ.get("SMALL_LLM_MODEL", "deepseek-v4-flash"),
temperature=0.1,
),
structured_output_mode=os.environ.get("STRUCTURED_OUTPUT_MODE", "json_object"),
)
embedder = OpenAIEmbedder(
config=OpenAIEmbedderConfig(
api_key=os.environ["OPENAI_API_KEY"],
base_url=os.environ.get("OPENAI_BASE_URL"),
embedding_model=os.environ.get("EMBEDDING_MODEL", "BAAI/bge-small-zh-v1.5"),
embedding_dim=int(os.environ.get("EMBEDDING_DIM", "512")),
)
)
graphiti = Graphiti(
uri=os.environ["NEO4J_URI"],
user=os.environ.get("NEO4J_USER", "neo4j"),
password=os.environ["NEO4J_PASSWORD"],
llm_client=llm_client,
embedder=embedder,
)
await graphiti.build_indices_and_constraints()
Neo4j 5.26.2 and Two-Replica Graphiti Kubernetes Manifest¶
Below is the complete sanitized manifest verified in namespace zep-lab, setting enableServiceLinks: false and explicit JVM heap/pagecache caps on StatefulSet/neo4j, and spreading replicas: 2 of Deployment/graphiti-api across worker nodes via topologySpreadConstraints:
apiVersion: v1
kind: Namespace
metadata:
name: zep-lab
---
apiVersion: v1
kind: Secret
metadata:
name: zep-secrets
namespace: zep-lab
type: Opaque
stringData:
NEO4J_PASSWORD: "<replace-with-strong-password>"
NEO4J_AUTH: "neo4j/<replace-with-strong-password>"
GRAPHITI_API_KEY: "<replace-with-random-api-key>"
OPENAI_API_KEY: "<replace-with-llm-gateway-token>"
---
apiVersion: v1
kind: Service
metadata:
name: neo4j
namespace: zep-lab
spec:
selector:
app: neo4j
ports:
- name: http
port: 7474
targetPort: 7474
- name: bolt
port: 7687
targetPort: 7687
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: neo4j
namespace: zep-lab
spec:
serviceName: neo4j
replicas: 1
selector:
matchLabels:
app: neo4j
template:
metadata:
labels:
app: neo4j
spec:
enableServiceLinks: false
securityContext:
fsGroup: 7474
fsGroupChangePolicy: OnRootMismatch
containers:
- name: neo4j
image: neo4j:5.26.2
ports:
- name: http
containerPort: 7474
- name: bolt
containerPort: 7687
env:
- name: NEO4J_AUTH
valueFrom:
secretKeyRef:
name: zep-secrets
key: NEO4J_AUTH
- name: NEO4J_server_memory_heap_initial__size
value: "512m"
- name: NEO4J_server_memory_heap_max__size
value: "1G"
- name: NEO4J_server_memory_pagecache_size
value: "512m"
- name: NEO4J_dbms_usage__report_enabled
value: "false"
readinessProbe:
httpGet:
path: /
port: 7474
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
livenessProbe:
httpGet:
path: /
port: 7474
initialDelaySeconds: 30
periodSeconds: 15
timeoutSeconds: 3
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: "2"
memory: 3Gi
volumeMounts:
- name: neo4j-data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: neo4j-data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: local-lvm
resources:
requests:
storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
name: graphiti-api
namespace: zep-lab
spec:
selector:
app: graphiti-api
ports:
- name: http
port: 8000
targetPort: 8000
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: graphiti-api
namespace: zep-lab
spec:
replicas: 2
selector:
matchLabels:
app: graphiti-api
template:
metadata:
labels:
app: graphiti-api
spec:
securityContext:
runAsUser: 1000
runAsGroup: 1000
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: graphiti-api
containers:
- name: graphiti-api
image: ghcr.io/example/graphiti-server:v0.32.1
ports:
- containerPort: 8000
env:
- name: NEO4J_URI
value: bolt://neo4j.zep-lab.svc.cluster.local:7687
- name: NEO4J_USER
value: neo4j
- name: NEO4J_PASSWORD
valueFrom:
secretKeyRef:
name: zep-secrets
key: NEO4J_PASSWORD
- name: GRAPHITI_API_KEY
valueFrom:
secretKeyRef:
name: zep-secrets
key: GRAPHITI_API_KEY
- name: OPENAI_API_KEY
valueFrom:
secretKeyRef:
name: zep-secrets
key: OPENAI_API_KEY
- name: OPENAI_BASE_URL
value: http://llm-gateway.mem0-lab.svc.cluster.local:8181/v1
- name: LLM_MODEL
value: deepseek-v4-flash
- name: SMALL_LLM_MODEL
value: deepseek-v4-flash
- name: EMBEDDING_MODEL
value: BAAI/bge-small-zh-v1.5
- name: EMBEDDING_DIM
value: "512"
- name: STRUCTURED_OUTPUT_MODE
value: json_object
- name: GRAPHITI_TELEMETRY_ENABLED
value: "false"
- name: SEMAPHORE_LIMIT
value: "4"
readinessProbe:
httpGet:
path: /healthcheck
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthcheck
port: 8000
initialDelaySeconds: 15
periodSeconds: 15
resources:
requests:
cpu: 250m
memory: 512Mi
limits:
cpu: "2"
memory: 2Gi
securityContext:
allowPrivilegeEscalation: false
Same-Cluster Verification and Head-to-Head Comparison with Mem0¶
To keep the comparison apples-to-apples, this benchmark shared the exact same Kubernetes cluster, LLM gateway, 512-dim offline BAAI/bge-small-zh-v1.5 embedder, and identical alice / bob / incident-2026-1203 messages as Mem0 on Kubernetes in Practice. Sanitized measurements are stored in results.json.

Figure 2: Head-to-head comparison of Mem0 v2.2.1 and Zep / Graphiti v0.32.1 on the same Kubernetes cluster across write latency, search latency, memory footprint, and multi-replica consistency.
Bi-Temporal Knowledge Graph Ingestion and Automatic Fact Invalidation¶
We ingested three Episodes with explicit reference_time values into group_id: "alice" (2026-06-01 initial profile -> 2026-12-01 team and coffee change -> 2026-12-03 GPU node incident), plus one control Episode into group_id: "bob":
| Episode | reference_time |
End-to-End Latency | LLM Calls | Nodes Extracted | Edges Extracted |
|---|---|---|---|---|---|
ep1_alice_initial |
2026-06-01T09:00:00Z |
61.75 s |
2 |
9 |
8 |
ep2_alice_transition |
2026-12-01T09:00:00Z |
73.62 s |
11 |
8 |
11 |
ep3_alice_incident |
2026-12-03T08:00:00Z |
87.71 s |
5 |
4 |
2 |
ep4_bob_profile |
2026-12-02T10:00:00Z |
35.83 s |
2 |
5 |
4 |
The resulting graph stored 22 Entity nodes, 4 Episodic provenance nodes, and 22 RELATES_TO edges (18 valid, 4 invalidated). Inside alice's 18 edges (14 valid, 4 invalidated), bi-temporal invalidation worked cleanly:
- Superseded facts received exact invalidation timestamps:
[INVALID] WORKS_AT:Alice 在广州的平台工程团队工作。(valid_at = 2026-06-01T09:00:00+00:00,invalid_at = 2026-12-01T09:00:00+00:00)[INVALID] DRINKS:Alice 早上只喝黑咖啡。(valid_at = 2026-06-01T09:00:00+00:00,invalid_at = 2026-12-01T09:00:00+00:00)- New and unchanged facts remained valid:
[VALID] WORKS_AT:Alice 刚转岗到上海的 AI 推理平台组工作。(valid_at = 2026-12-01T09:00:00+00:00,invalid_at = null)[VALID] DRINKS:Alice 最近改喝燕麦拿铁。(valid_at = 2026-12-01T09:00:00+00:00,invalid_at = null)[VALID] HAS_ALLERGY:Alice 对花生严重过敏。(valid_at = 2026-06-01T09:00:00+00:00,invalid_at = null)
Honest edge-case note: in
ep2, because the input explicitly contained negative clauses ("no longer drinks black coffee"), the LLM both marked the old edgeINVALIDand emitted a redundant negation edgeAlice 不再喝黑咖啡。which was immediately markedINVALIDas well (4invalidated edges total). For high-precision domains, constrain extraction with custom Pydantic entity and edge ontologies.
Running MATCH (a:Entity {group_id: 'alice'})-[r:RELATES_TO]->(b:Entity {group_id: 'alice'}) RETURN a, r, b LIMIT 25 in Neo4j Browser (:7474) visualizes the live entity-relationship graph directly around Alice:

Figure 3: Live light-mode screenshot from Neo4j 5.26.2 Browser running on Kubernetes, visualizing the entities and RELATES_TO edges Graphiti built for alice.
Hybrid Search Latency, Valid-Only Filtering, and Group Isolation¶
On reads, Graphiti leverages 32 auto-managed Neo4j indexes (including RANGE indexes on valid_at / invalid_at / group_id and Lucene FULLTEXT indexes on edge_name_and_fact / node_name_and_summary) to fuse vector similarity, BM25, and graph neighborhood via RRF with 0 LLM calls:
- Search latency: five consecutive queries for
"Which GPU incident happened on node-02?"ran in101.7 / 212.1 / 128.1 / 68.3 / 101.1 ms(5-run median101.7 ms—essentially matching Mem0Bearer JWTat99.0 msand nearly6×faster than Mem0X-API-Keyat598.0 ms). - Valid-only filtering: querying
"What coffee does Alice drink and any allergy?"returned5edges withonly_valid=falseand narrowed cleanly to3currently valid edges withonly_valid=true. - Strict group isolation: querying
"alice peanut allergy"withgroup_ids=["bob"]returned onlybob's edges with0cross-group leaks.
Two-Replica Stateless Consistency and Pod Deletion Recovery¶
This test highlights the sharpest Kubernetes operational contrast between Graphiti and Mem0:
- Zero split-brain across 2 replicas: querying
graphiti-apiPod 1 (120.9 MiBRSS) and Pod 2 (125.9 MiBRSS) on separate worker nodes returned identicalalicegraph counts (total: 18, valid_count: 14, invalidated_count: 4). - Zero-downtime single-Pod drain: while running
kubectl delete pod <pod1>,5/5concurrent API calls returnedHTTP 200, and Kubernetes restored2/2Ready in11.63 s. neo4j-0deletion recovery: afterkubectl delete pod neo4j-0, the Neo4j JVM reached Ready in28.56 s(~3.5×slower than PostgreSQL 17's8.09 s) and succeeded on the1st query at31.49 swith all22entities,4episodes, and22bi-temporal edges intact.
Full Side-by-Side Comparison: Mem0 vs. Zep on Kubernetes¶
| Dimension (Same Cluster, Models, and Corpus) | Mem0 v2.2.1 (pgvector 0.8.7) |
Zep / Graphiti v0.32.1 (Neo4j 5.26.2) |
|---|---|---|
| Core resident memory (excl. embedder) | 488.0 MiB (PG17 + API + Dashboard) |
1,118.2 MiB (Neo4j 871.4 + 2×API 246.8) |
| Turn 1 initial write latency / LLM calls | 3.64 s / 1 call |
61.75 s / 2 calls |
| Turn 2 state-change latency / LLM calls | 5.84 s / 1 call |
73.62 s / 11 calls |
| Superseded fact handling | Additive transition note; old row stays active | Auto-stamps invalid_at, supports only_valid filter |
| Default extraction language for Chinese input | Translates to English (penalizes lightweight CN embedders) | Preserves native Chinese entities and facts |
Search 5-run median (0 LLM calls) |
99.0 ms (JWT) / 598.0 ms (X-API-Key bcrypt) |
101.7 ms (SHA-256 auth + hybrid RRF) |
| Stateless multi-replica API scaling | Blocked by local SQLite history.db & config drift |
Natively stateless; 2/2 consistent, 0-downtime drain |
| Database Pod delete to Ready | 8.09 s (PostgreSQL 17) |
28.56 s (Neo4j 5.26 JVM) |
| Built-in Web UI | Next.js 15 Dashboard (audit log & entities) | No dedicated memory UI; uses Neo4j Browser |
Four Real Kubernetes Pitfalls and Security Hardening¶
Naming the Service neo4j Crashes Startup Validation¶
Symptom: deploying StatefulSet/neo4j alongside Service/neo4j threw neo4j-0 into CrashLoopBackOff with Unrecognized setting. No declared setting with name: PORT.7687.TCP.PORT.
Root cause: Kubernetes injects <SERVICE>_PORT_* environment variables into Pods in the same namespace. When a Service is named neo4j, NEO4J_PORT_7687_TCP_PORT gets parsed by Neo4j 5.x's entrypoint as a neo4j.conf setting and fails strict validation. Because StatefulSet RollingUpdate waits for Pod 0 to become Ready, patching the manifest also requires deleting the stuck Pod once.
Fix: set enableServiceLinks: false in StatefulSet/neo4j's Pod spec to disable service-link env var injection completely.
Upstream Reference Server Ignores Custom Gateways and json_object Mode¶
Symptom: upstream server/graph_service/zep_graphiti.py fails to propagate OPENAI_BASE_URL and EMBEDDING_MODEL_NAME to AsyncOpenAI and OpenAIEmbedder, and defaults to OpenAIClient (which expects OpenAI Responses API / json_schema constrained decoding unsupported by DeepSeek or many vLLM deployments).
Fix: instantiate OpenAIGenericClient(structured_output_mode="json_object") and OpenAIEmbedder with explicit base_url and embedding_dim, and manage a singleton Graphiti driver inside FastAPI lifespan instead of opening and closing Neo4j Bolt pools per request.
Long Write Tail Latency and Durable Async Queues¶
Because ingesting a state-transition Episode takes 35–88 s (2–11 LLM calls), foreground chat APIs must never block on add_episode(). At the same time, upstream routers/ingest.py's in-memory asyncio.Queue silently drops pending jobs on Pod restarts or OOMs.
Fix: publish conversation events from foreground services into a durable queue (Kafka / Redis Streams / NATS) and run dedicated graphiti-worker consumers calling add_episode() sequentially per group_id, bounding upstream LLM concurrency with SEMAPHORE_LIMIT.
Unauthenticated Reference Server and Neo4j JVM Sizing¶
- Enforce auth before exposure: never expose stock
zepai/graphitidirectly; put JWT / OIDC auth on an API gateway (Higress / Envoy) or enforce constant-time SHA-256X-API-Keyvalidation in your wrapper (eliminating both unauthenticated graph wipes andbcrypt's480 mstax). - Size Neo4j JVM explicitly: even with a tiny graph, Neo4j consumed
871.4 MiBRSS; always capNEO4J_server_memory_heap_max__sizeandpagecache_sizewith at least512 MiBheadroom below Podlimits.memory, and restrict:7687tographiti-apiviaNetworkPolicy. - Lighter graph backend option: if cluster RAM is tight and Neo4j Browser is unnecessary, switch
db_backendto officially supported FalkorDB (Redis-based module with lower idle memory), weighing its backup and tooling maturity against Neo4j.
Selection Advice: When to Choose Mem0 vs. Zep¶
Based on same-cluster measurements, the trade-off boundary is crisp:
- Choose Mem0
v2.2.1when you want low write cost and fast ingestion (1LLM call,3–6 s), an out-of-the-box Web Dashboard with audit logs, a compact< 500 MiBmemory envelope, and flat profile/preference memory (pair withBearer JWTor SHA-256 API-key hashing). - Choose Zep / Graphiti
v0.32.1when your domain demands strict bi-temporal fact invalidation (invalid_at) (support ticket state tracking, engineering change/incident causality, point-in-time compliance audits), stateless multi-replica zero-downtime API scaling, and you can accommodate asynchronous background ingestion plus higher LLM token and Neo4j memory budgets.
Summary¶
Deploying Graphiti v0.32.1 + Neo4j 5.26.2 on Kubernetes and benchmarking it head-to-head against Mem0 v2.2.1 on the exact same cluster proved both Graphiti's strengths—automatic bi-temporal invalidation (invalid_at), 101.7 ms zero-LLM hybrid search, and stateless 2-replica zero-downtime scaling—and its four production hurdles: enableServiceLinks: false to avoid Neo4j env-var crashes, fixing upstream reference-server auth and custom-gateway wiring, fronting 35–88 s writes with a durable message queue, and sizing Neo4j JVM memory cleanly. Together, these two hands-on studies establish a concrete engineering ledger for choosing between vector memory (Mem0) and bi-temporal graph memory (Zep / Graphiti) on Kubernetes.