Knowledge Graphs Are Quietly Replacing RAG
From the publisher’s feed, collected in the ZeroLabs newsroom.
Why the next generation of AI systems is moving beyond vector search toward structured knowledgecreated by GEMINIIt’s 2 a.m. and an on-call engineer is staring at a failing deployment. She opens the company’s internal AI assistant and asks: “What breaks if I change the retry timeout in the payments-gateway service?"The assistant — built on a well-tuned RAG pipeline, chunked documentation, a fast vector database, a capable LLM — comes back fast and confident. It quotes the payments-gateway README. It cites a paragraph about retry policies.It’s also wrong, in the specific way RAG systems tend to be wrong: not fabricated, just incomplete. It has no way of knowing that payments-gateway is called synchronously by checkout-service, that checkout-service's SLA depends on exactly that timeout, or that this same config change caused an incident eleven months ago whose postmortem lives in a doc that shares almost no vocabulary with the one it just retrieved. Nothing it said was false. It just couldn't see the shape of the system it was answering questions about.That’s the limitation a lot of teams are quietly hitting as RAG stops being a demo and starts being infrastructure. It’s not a prompting problem. It’s not a context-window problem. It’s a representation problem: vector similarity tells you what two pieces of text are about. It tells you nothing about how the things they describe relate. And relationships are exactly what systems-level questions are made of.That’s the actual reason knowledge graphs are back — not as a RAG replacement, but as the structural layer that lets retrieval reason instead of just recall. This piece walks through why that matters, where the hype gets ahead of the evidence, and how to actually build the hybrid version yourself.What RAG Solved — and Why It Was Genuinely GoodRAG, as formalized by Lewis et al. in 2020, solved a real problem: LLMs are frozen at training time and will confidently hallucinate about anything that happened after, or was never in the training set to begin with. Instead of asking a model to memorize everything, RAG lets it look things up at inference time.The pipeline is now familiar enough to be boring, which is a compliment:Chunking splits documents into passages small enough to be individually retrievable, large enough to keep local context intact.Embeddings turn each chunk into a vector, positioned so that semantically similar text lands close together regardless of exact wording.A vector database (HNSW, IVF-based indexes) makes nearest-neighbor search over millions of those vectors fast.Similarity search retrieves the top-k chunks closest to the embedded query.Context injection drops those chunks into the prompt so the model answers from sourced text instead of parametric memory alone.┌─────────────┐ ┌────────────┐ ┌─────────────────┐│ Documents │────▶│ Chunking │────▶│ Embedding │└─────────────┘ └────────────┘ │ Model │ └────────┬─────────┘ │ ▼ ┌─────────────────┐ │ Vector Store │ │ (HNSW / IVF) │ └────────┬─────────┘ │ User Query ──▶ Embed Query ──▶ ANN Search ─┘ │ ▼ Top-k Chunks ──▶ LLM + Prompt ──▶ AnswerFor open-domain question answering, where the answer lives inside one passage, this is still the right architecture. Cheap to stand up, scales horizontally, works with off-the-shelf embedding models. If your product is “search my docs,” don’t let this article talk you out of it.The trouble starts exactly where the question stops being about a passage and starts being about the structure connecting many passages.Practical tip: if you’re building your first RAG system, don’t pre-optimize chunking strategy before you have failure data. Ship fixed-size chunks with overlap, measure against real queries, and only invest in smarter chunking once you can point at a specific failure it would fix.Where RAG Actually BreaksRAG’s failure modes aren’t bugs. They’re what happens when a proxy for relevance gets pushed past what it can represent.Chunking severs structure. A clause reading “this applies only to enterprise-tier customers” can land in a different chunk than the policy it modifies. The retriever happily returns the policy without its own exception.Similarity isn’t relationship. “Service A calls Service B” and “Service A is unrelated to Service B” can produce near-identical embeddings — both sentences mention the same two names in similar prose. Vector search has no concept of direction or dependency, only co-occurrence in meaning-space.Enterprises accumulate the same fact three times, disagreeing with itself. A Slack thread, a wiki page, and a Confluence doc describe the same policy differently, none marked as canonical. RAG retrieves all three with no idea which one supersedes the others.Sparse retrieval invites hallucination. When the retriever returns weakly relevant chunks — common with rare entities, acronyms, or long-tail phrasing — models tend to fill the gap with something plausible rather than admitting uncertainty.Long-context stuffing isn’t a fix. Research on “lost in the middle” effects shows LLMs disproportionately attend to the start and end of long contexts. Retrieving more chunks to compensate for uncertain retrieval often just dilutes the passages that actually mattered.And multi-hop questions are the real ceiling. Take: “Which customers are affected by the outage in the region where our EU data processor is located?” Answering that means chaining facts across the incident report, the data-processor registry, and the customer-region mapping — three documents that may share almost no vocabulary with each other or the query. Vector search finds documents about the question. It doesn’t compose chains of fact the question actually requires.A legal-AI example makes this concrete: “which of our contracts are affected if Vendor X’s parent company is acquired” requires traversing a corporate ownership graph and a contract-vendor mapping — two structurally distinct relationships that no single passage states together. RAG will retrieve every contract that mentions Vendor X by name, and stop there, because that’s all it knows how to do.Enter Knowledge GraphsA knowledge graph represents information as entities (nodes) connected by typed relationships (edges), constrained by an ontology — a schema defining what kinds of entities and edges are allowed to exist.Nodes are things: a service, a customer, a contract clause, a regulation. Edges are directional and typed: DEPENDS_ON, OWNED_BY, SUPERSEDES, LOCATED_IN. The ontology is what keeps the graph from becoming a junk drawer — it defines what a Service node must have, what a DEPENDS_ON edge is allowed to connect.The reasoning payoff is real: if A DEPENDS_ON B and B DEPENDS_ON C, a graph traversal derives that a failure in C may affect A — without that fact ever being written down anywhere. That's not retrieval. That's inference over structure.Here’s the part worth internalizing before anything else in this article: embeddings and graphs aren’t competing answers to the same question. They’re answers to two different questions that both happen to get called “retrieval.”What Structured Knowledge Actually UnlocksMost “why graphs matter” lists read like a press release — memory, explainability, reasoning, repeat. The honest version is narrower: graphs change what you can ask, and they change whether you can prove your answer is right.Explainability is the big one, and it’s not soft. A graph traversal is a path you can print: Incident-4471 → CAUSED_BY → Service-Timeout → AFFECTS → payments-gateway. That's auditable in a way "the model attended to these five chunks" simply isn't — and in a regulated industry, "we can't fully explain why the system said that" is not an acceptable answer, no matter how good the accuracy metrics look.Multi-hop reasoning stops being an LLM party trick. With RAG, chaining facts across documents depends on the model correctly inferring a connection nobody wrote down. With a graph, the chain is the data structure — the reasoning is guaranteed by the traversal, not hoped for from the model.Persistent, cross-session memory becomes possible. An agent backed by a graph accumulates institutional knowledge the way a colleague does — “Project Atlas” is the same node whether it showed up in Jira, Slack, or a design doc last week or six months ago, not three semantically-similar-but-disconnected fragments.Everything else — code intelligence, documentation, lineage, compliance — is really a specific instance of one of those three things. Code is a call graph and an import graph; documentation about systems-of-systems is entity relationships wearing prose; lineage and compliance are both, at bottom, “prove the connection, exhaustively, on demand.” I’ll go deeper into three of these in the use-cases section below rather than listing all nine here — the list version tells you graphs are relevant everywhere, which is true and also not that useful.RAG vs. Knowledge Graphs, HonestlyNo single row here favors one architecture outright — read this as a trade-off surface, not a scoreboard.Practical tip: don’t pick a side before you have a query taxonomy. Log a sample of real user queries for two or three weeks, hand-classify them into lookup / fuzzy-recall / relational-multi-hop, and let that distribution decide how much graph investment is actually justified. Most teams skip this step and end up either over-building a graph nobody’s questions need, or under-building one their actual traffic is crying out for.The Current LandscapeGraphRAG is a pattern, not a product: use an LLM to extract entities and relationships from unstructured text, build a graph, then combine graph traversal with vector search at query time. Microsoft Research’s open GraphRAG approach is notable for generating LLM summaries over graph communities, which handles broad corpus-level questions that top-k retrieval genuinely can’t.Neo4j is the most widely deployed property-graph database — mature Cypher query language, good tooling, increasingly direct LLM integrations. Memgraph targets lower-latency, in-memory graph analytics, also Cypher-compatible, and is the one to reach for if your traversals need to be closer to real time than Neo4j’s disk-backed model comfortably gets you.RDF, the W3C standard for subject-predicate-object triples with formal OWL semantics, is the older, stricter option — still dominant in domains that need formal logical reasoning (life sciences, government linked data), less common in day-to-day product engineering because the rigor costs you iteration speed.Property graphs — what Neo4j and Memgraph actually use — trade some of RDF’s formal strictness for the ability to attach arbitrary properties directly to nodes and edges. For most application-layer work, that trade is worth it.MCP matters here for a specific reason: it turns “let an agent query our knowledge graph” from a bespoke integration per model provider into exposing one MCP server. That’s not a small thing — it’s the difference between a graph tool you build once and one you rebuild every time you swap models.Extraction pipelines are the unglamorous layer that actually determines whether any of this works: LLM-based entity/relation extraction, followed by entity resolution — deciding “J. Smith” in one doc and “Jane Smith” in another are the same node — and validation against the ontology. This layer gets the least attention and causes the most production pain. More on that below.The Realistic Architecture: Hybrid, Not Either/OrIf there’s one claim in this piece I’d defend hardest, it’s this: “graphs replace RAG” is a bad headline for a good idea. What’s actually happening is that retrieval is becoming a portfolio — a planner deciding, per query, which tool actually answers the question in front of it.┌──────────────────────────┐ │ Agent / Planner │ └────────────┬──────────────┘ │ ┌─────────────────┬──────────┼───────────┬─────────────────┐ ▼ ▼ ▼ ▼ ▼┌───────────────┐ ┌───────────────┐ ┌────────┐ ┌────────────┐ ┌───────────────┐│ Vector Search │ │ Knowledge │ │ Tools │ │ Long-term │ │ Structured ││ (semantic │ │ Graph │ │ (APIs, │ │ Memory │ │ Data / SQL ││ recall) │ │ (traversal) │ │ code) │ │ Store │ │ Warehouse │└───────┬───────┘ └───────┬───────┘ └───┬────┘ └─────┬──────┘ └──────┬────────┘ │ │ │ │ │ └─────────────────┴─────────────┴────────────┴───────────────┘ │ ▼ Context Assembly (merge, dedupe, rank) │ ▼ LLM (reason + generate)In practice, the highest-leverage version of this isn’t five tools running in parallel every time — it’s one specific pattern: vector search to seed, graph to expand. Embed the query, retrieve the handful of entities it matches best, then traverse outward from those entities in the graph for the neighborhood similarity search alone would never have found. It’s cheaper than always querying everything, and it maps naturally onto how most real questions actually start — with something the user named, expanding into something they didn’t know to ask about.Where This Actually Pays Off (Three Deep, Not Nine Shallow)Software engineering assistants. A call graph and a dependency graph turn “what breaks if I change this” from a documentation-search problem into a traversal query. This is the clearest, least controversial win in the whole list — every large engineering org already half-builds this informally (service catalogs, ownership wikis), and a real graph just makes it queryable instead of tribal knowledge.Cybersecurity. Alert logs are semantically similar to each other constantly — that’s what makes them noisy — but causally distinct. A vector index will tell you which alerts read alike. An attack graph tells you which hosts an attacker could actually reach next, which is the question a security team is really asking. This is a case where RAG isn’t just weaker, it’s answering a different question than the one that matters.Financial analysis. Ownership and counterparty structure is inherently relational — subsidiaries, exposure, contagion paths. A graph answers “what’s our concentration risk if this counterparty defaults” directly. RAG over the same filings will find you documents that mention the counterparty, and leave the actual exposure chain for a human to reconstruct by hand.The pattern across all three, and the six I’m not expanding on here (legal, healthcare, research, digital twins, manufacturing, customer support), is the same one from section one: RAG struggles precisely where the question is about structure rather than content. A graph is, by definition, a structure. That’s not a coincidence — it’s the whole argument of this article in one sentence.Building It: A Real Shape, Not a Toy RepoHere’s a working shape for a first system: Neo4j for the graph, MCP to expose graph tools to the model, LangGraph for routing between graph and vector paths, FastAPI to serve it. I’m being upfront that what follows is a functional skeleton you’d need to harden, not a drop-in production repo — anyone promising you a 200-line “build your own GraphRAG” that just works has skipped the extraction-quality problem, which is where all the real difficulty lives.Extraction — turn documents into graph data:pythonfrom anthropic import Anthropicimport jsonclient = Anthropic()EXTRACTION_PROMPT = """Extract entities and relationships from the text below.Return ONLY JSON: {{"entities": [{{"id": str, "type": str, "name": str}}],"relationships": [{{"source": str, "target": str, "type": str}}]}}Allowed entity types: Service, Team, Incident, DependencyAllowed relationship types: DEPENDS_ON, OWNED_BY, CAUSED_BYText:{document_text}"""def extract_graph(document_text: str) -> dict: response = client.messages.create( model="claude-sonnet-4-6", max_tokens=1500, messages=[{"role": "user", "content": EXTRACTION_PROMPT.format(document_text=document_text)}] ) return json.loads(response.content[0].text)Loading — this is where most first attempts quietly break:pythonfrom neo4j import GraphDatabasedriver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))def load_graph(graph_data: dict): with driver.session() as session: for entity in graph_data["entities"]: session.run( f"MERGE (n:{entity['type']} {{id: $id}}) SET n.name = $name", id=entity["id"], name=entity["name"] ) for rel in graph_data["relationships"]: session.run( f"""MATCH (a {{id: $source}}), (b {{id: $target}}) MERGE (a)-[r:{rel['type']}]->(b)""", source=rel["source"], target=rel["target"] )Use MERGE, never CREATE, on both entities and relationships. LLM extraction will re-emit the same entity across dozens of documents — without MERGE you get silent duplicate nodes instead of one canonical node accumulating edges. This is the single bug that kills more first-pass graph pipelines than every other mistake on this list combined.Exposing traversal as an MCP tool:pythonfrom mcp.server import Serverserver = Server("graph-tools")@server.tool()async def query_dependencies(service_name: str) -> str: """Everything a given service depends on, transitively, up to 3 hops.""" with driver.session() as session: result = session.run( """MATCH (s:Service {name: $name})-[:DEPENDS_ON*1..3]->(dep) RETURN DISTINCT dep.name AS dependency""", name=service_name ) return json.dumps([r["dependency"] for r in result])Routing between graph and vector paths. The honest version of this step: the “planner” is a single LLM call classifying the query, not a learned policy. Don’t over-build this early —pythonROUTE_PROMPT = """Classify this question as one of: GRAPH, VECTOR, BOTH.GRAPH = asks about dependencies, ownership, or relationships between named things.VECTOR = asks for similar/related unstructured content, no specific relationship implied.Question: {question}Answer with one word."""def route(question: str) -> str: resp = client.messages.create( model="claude-sonnet-4-6", max_tokens=10, messages=[{"role": "user", "content": ROUTE_PROMPT.format(question=question)}] ) return resp.content[0].text.strip()def answer(question: str): route_decision = route(question) graph_ctx = query_dependencies(extract_service_name(question)) if route_decision in ("GRAPH", "BOTH") else None vector_ctx = vector_search(question) if route_decision in ("VECTOR", "BOTH") else None return synthesize(question, graph_ctx, vector_ctx)That’s a real, if minimal, decision function — not a placeholder. It won’t handle ambiguous or compound questions well yet, and extract_service_name still needs its own small NER step, but it's the actual shape you'd deploy first and improve from measured failures, which is a better starting point than a more elaborate design you haven't tested against real queries yet.The Costs Nobody Puts in the Slide DeckTeams that adopt graphs without budgeting for these tend to abandon them within a year — usually quietly, by letting the graph go stale rather than announcing the failure.ChallengeWhy it actually bitesEntity resolutionDeciding two mentions are the same real-world thing is an ongoing problem, not a one-time scriptOntology designGet the schema wrong early and you’re migrating it later — this is database schema design, not prompt engineeringGraph driftAuto-extracted edges accumulate wrong or outdated relationships with no built-in invalidationMaintenanceSystems change faster than most teams update the graph describing them — staler than a vector index, and less obviously soCostExtraction, validation, and human review of edges are real ongoing engineering spend that vector-only RAG simply doesn’t requireSecurityTraversal can expose relationship data that no single document, read alone, would revealData qualityA bad extraction pipeline produces confidently wrong traversal results — and wrong-but-confident is harder to catch than “no results found”The honest summary: a graph moves effort from retrieval-time uncertainty, which is RAG’s problem, to ingestion-time rigor, which is the graph’s problem. That’s a genuinely good trade for a system that answers relational questions every day. It’s a bad trade for a system that mostly needs to find documents that sound like the question. Most of the “graphs didn’t work for us” stories I’ve seen are really “we built a graph for fuzzy-recall traffic” stories.Where This GoesThe direction that’s actually happening, not speculative: agentic systems that maintain an evolving model of the entities and relationships they operate over, across sessions, rather than re-deriving context from scratch every conversation. A graph is a natural substrate for that kind of persistent memory in a way a rolling context window structurally can’t be.The part that’s a genuine prediction, not a settled fact: as agents take on more autonomous, multi-step work, the demand for traceable reasoning will probably push more systems toward graph-backed traversal, especially anywhere “why did it answer that way” has to be an auditable answer rather than an approximate one. Whether well-maintained knowledge graphs become something as standard as a data warehouse — core infrastructure every AI system in a company draws on — is a real open question, and it hinges on something unglamorous: whether entity resolution and extraction quality get cheap enough that maintaining a graph stops being a specialized discipline. Right now it still is one.What isn’t speculative is the competitive-advantage argument, and it’s worth being specific about why: anyone can stand up a vector index over their docs in an afternoon. Almost nobody has a clean, current model of how their systems, contracts, and customers actually connect. That gap — not the graph technology itself — is where the durable advantage sits.Key TakeawaysRAG solved open-domain grounding well. Its ceiling is structural: similarity approximates aboutness, not relationship, so multi-hop questions expose it every time.Knowledge graphs make relationships explicit and traversable, buying you deterministic reasoning and an auditable answer path — not just “better retrieval.”The realistic architecture is hybrid: vector search to find where to start, graph traversal to expand from there — not graphs replacing embeddings wholesale.The real cost of a graph isn’t the database. It’s entity resolution and ongoing maintenance, and it never fully goes away.Classify your actual query traffic before investing — relational, multi-hop questions justify a graph; mostly-fuzzy recall usually doesn’t.MCP is becoming the standard way to expose graph tools to agents without rebuilding the integration per model provider.The gap that matters isn’t graph vs. vector database — it’s whether you have a clean model of how your business actually connects at all.Knowledge Graphs Are Quietly Replacing RAG was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.