Agent Knowledge Graphs

Production-grade guide to agent knowledge graphs covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Agent Knowledge Graphs provide a structured, traversable representation of an agent's accumulated experiences, facts, and relationships between entities. They matter when an agent must reason over long‑term context, deduplicate contradictory memories, or share knowledge across sessions without re‑computing from scratch. This reference page covers how to set up a graph‑backed store, query it efficiently, and avoid the failure modes that catch teams off‑guard when moving from in‑memory caches to persistent graph layers.

Initializing a Knowledge Graph Backend

Most agent systems begin with an in‑memory dict or a KV store. When the agent needs to query relationships—e.g., "which other agents has this user collaborated with?"—a flat key‑value store falls short. A relational database with a well‑designed schema can serve as a lightweight knowledge graph backend without requiring a separate graph engine.

Schema patterns for agent facts

The most common pattern is an adjacency‑list table: one row per fact, with columns for the subject, predicate, object, and metadata. Here is a concrete schema you can create with psql:

CREATE TABLE agent_facts (
  id BIGSERIAL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  subject TEXT NOT NULL,
  predicate TEXT NOT NULL,
  object TEXT,
  source TEXT,
  created_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE (agent_id, subject, predicate, object)
);
CREATE INDEX ON agent_facts (agent_id, predicate);
CREATE INDEX ON agent_facts (subject, predicate, object);

Apply these with:

psql -c "CREATE TABLE agent_facts (
  id BIGSERIAL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  subject TEXT NOT NULL,
  predicate TEXT NOT NULL,
  object TEXT,
  source TEXT,
  created_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE (agent_id, subject, predicate, object)
);"
psql -c "CREATE INDEX ON agent_facts (agent_id, predicate);"
psql -c "CREATE INDEX ON agent_facts (subject, predicate, object);"

If you are using a managed service, replace psql with the service‑specific CLI—the SQL syntax itself is portable.

Loading initial facts

After the table exists, seed it with the agent's first‑order knowledge. A typical load might come from an export file or a bootstrap script. Here is a real‑world psql command that inserts a batch of facts from a TSV file:

psql -d agentdb -c "\copy agent_facts(agent_id,subject,predicate,object,source,created_at) FROM '/data/agent-facts.tsv' WITH (FORMAT csv, DELIMITER E'\\t', HEADER true);"

The \copy command streams the file directly into the table without pulling the data into the client process first, which matters when the fact set grows into the millions of rows.

Querying and Traversing Agent Knowledge

Once facts are persisted, the reader's next intent is usually to retrieve them—either by exact match or by traversing relationships. Recursive queries in SQL can express simple graph traversals without a separate traversal engine.

Retrieving direct facts

A straightforward equality lookup is the most common pattern:

psql -d agentdb -c "SELECT object, source, created_at FROM agent_facts WHERE agent_id = 'agent-42' AND predicate = 'cites';"

Expected output (truncated):

 object   | source          | created_at
 --------------------------------
 paper-17 | external-db     | 2024-06-12 14:33:21+00
 paper-42 | internal-log    | 2024-06-13 08:11:09+00
 (2 rows)

Recursive traversal of multi‑hop relationships

To find all facts reachable within N hops from a starting node, use a recursive common table expression. The following query walks up to three hops from a given subject, collecting every predicate‑object pair encountered:

psql -d agentdb -c "
WITH RECURSIVE walk AS (
  SELECT object AS node, predicate AS edge, ARRAY[object] AS visited
  FROM agent_facts
  WHERE agent_id = 'agent-42' AND predicate = 'mentions'
  UNION ALL
  SELECT f.object, f.predicate, walk.visited || f.object
  FROM agent_facts f, walk
  WHERE f.agent_id = walk.node
    AND f.predicate = 'mentions'
    AND NOT f.object = ANY(walk.visited)
)
SELECT DISTINCT node, edge FROM walk;
"

If the recursion depth exceeds the database's default limit, you may see output such as:

ERROR: recursion detected at depth 1000
HINT: Increase max_recursion_depth if you need more hops.

Consult your database documentation for the session‑level parameter to raise the cap if deeper traversal is required.

Filtering traversals by time or source

Often you only want facts created within a certain window, or from a trusted source. Append WHERE clauses to the recursive branch:

psql -d agentdb -c "
WITH RECURSIVE walk AS (
  SELECT object AS node, predicate AS edge, ARRAY[object] AS visited, created_at AS ts
  FROM agent_facts
  WHERE agent_id = 'agent-42' AND predicate = 'mentions' AND created_at >= now() - interval '30 days'
  UNION ALL
  SELECT f.object, f.predicate, walk.visited || f.object, f.created_at
  FROM agent_facts f, walk
  WHERE f.agent_id = walk.node
    AND f.predicate = 'mentions'
    AND NOT f.object = ANY(walk.visited)
    AND f.created_at >= now() - interval '30 days'
)
SELECT DISTINCT node, edge FROM walk;
"

Persisting and Versioning Graph State

Knowledge graphs in production require backups, change tracking, and the ability to roll back to a previous understanding of the world.

Snapshot‑based backups using psql \copy

A consistent point‑in‑time snapshot is the simplest backup strategy. The following psql \copy command exports the entire agent_facts table as CSV, suitable for later re‑import or archival:

psql -d agentdb -c "\copy agent_facts TO '/tmp/agent-facts-$(date +%s).csv' WITH (FORMAT csv, HEADER true);"

To re‑import from such a snapshot:

psql -d agentdb -c "\copy agent_facts FROM '/tmp/agent-facts-1718073600.csv' WITH (FORMAT csv, HEADER true);"

Incremental tracking with Git

For teams that treat agent knowledge as code, storing migration files in a Git repository is common. A typical workflow:

git add agents/knowledge/graph.sql
git commit -m "add follows-edge schema for v1.3.2"
git push origin main

The corresponding psql apply step in CI:

psql -h db-host -U deploy -d agentdb -f agents/knowledge/graph.sql

If the migration fails mid‑stream, psql exits with code 3 and leaves the schema in a partially applied state. Always wrap migration scripts in transactions or use psql --single-transaction to ensure all‑or‑nothing application.

psql --single-transaction -h db-host -U deploy -d agentdb -f agents/knowledge/graph.sql

Sharp Edges: What Silently Fails and How to Detect It

Moving from an in‑memory agent memory to a persistent graph layer introduces several failure modes that do not surface during local development but surface under load or after weeks of operation.

Recursion depth limits

Recursive CTEs in many relational database systems cap at a default depth (commonly 1000 iterations). Deep inheritance or circular reference patterns in agent graphs can hit this limit, producing an error such as "ERROR: recursion detected at depth 1000". The failure is silent in the sense that the query simply stops returning rows beyond the cap, potentially leaving the agent with an incomplete view of its knowledge neighborhood. Consult your database documentation for the session‑level parameter to increase the depth if unbounded hops are required; alternatively, restructure the query to use a WHILE loop in your application code.

Index maintenance and write latency

The UNIQUE (agent_id, subject, predicate, object) constraint enforces dedup, but every insert must traverse the index. On tables with high write throughput, insert latency can degrade if the index is not periodically reorganized. Schedule regular index maintenance appropriate to your database system—many platforms provide an automatic cleanup process, but relying on defaults without monitoring can lead to gradual query slowdown. A practical heuristic is to run ANALYZE after every 10k row changes, or integrate it into your deployment migration pipeline.

Predicate name collisions across agent namespaces

If multiple agents share the same database schema, predicate strings like "role" or "status" can collide, producing cross‑agent contamination in traversals. A common mitigation is to prefix predicates with the agent identifier: "agent-42/role", "agent-42/status". This pattern is invisible to the SQL engine but prevents logical overlap when queries are composed across agent identities.

Connection pool exhaustion under concurrent traversal

Recursive queries tend to hold connections for the duration of the hop count. In a system where many agents simultaneously issue multi‑hop traversals, the connection pool can drain faster than expected, leading to errors such as "FATAL: remaining connection slots are reserved for non‑superuser roles". Monitor your database's equivalent of pg_stat_activity for queries in active state lasting longer than your typical network RTT, and adjust max_connections or pool size accordingly.

Timestamp skew in time‑filtered traversals

The schema defaults to TIMESTAMPTZ, which databases convert to UTC internally. If your agent processes run across hosts in different time zones and you filter by created_at >= now() - interval '30 days', mismatched client‑side clock settings can cause facts to appear or disappear from traversal results without any data change. Always store timestamps at the agent process level in UTC, and never rely on now() from a client with an unsynchronized clock.

Summary of gotchas

These are the edges you only learn after the first production incident, and having a checklist (like the one above) reduces mean‑time‑to‑detection.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.