Skip to main content

08. Programming & Technologies

SQL and NoSQL Databases for Agent Backends

Agent backends need durable storage beyond the prompt: SQL for transactional product data, document/key-value NoSQL for flexible run state and caches, and append-only audit logs for tool calls. Vector DBs come next for RAG β€” this lesson is the system of record and session spine behind safe agent tools.

What you will learn

  • Choose SQL vs document vs key-value for agent data
  • List what to persist for runs, memory, and audit
  • Design safe parameterized DB tools with authZ
  • Avoid raw-SQL tools and unbounded reads
  • Answer interview questions with short, solid answers
SQL document NoSQL and key-value for agent backends
Interview staple: SQL for truth; docs/KV for flexible run state; vectors are a later lesson.

Definition

SQL (relational) databases store structured tables with schemas, joins, and ACID transactions β€” ideal for users, tickets, orders, and permissions. NoSQL covers document stores (flexible JSON), key-value/caches (Redis-style TTL state), and related models. Agent backends usually combine them: relational truth + fast session/cache + optional documents for messy payloads.

This is not the embeddings/vector lesson. Systems of record and run telemetry live here; semantic search stores come next.

Introduction

This lesson (#5 in Programming & Technologies) follows REST/HTTP/JSON. APIs often persist into databases; agent tools must do the same safely under retries and multi-step runs.

Next: Vector Databases for Agents (Pinecone, Chroma, FAISS, Weaviate).

Why databases matter for agents

  • Prompts are not durable memory across crashes or devices
  • Tool side effects need transactional integrity
  • Audit trails explain what the agent changed and why
  • Checkpoints/resume need stored run state
  • Multi-tenant products need row-level isolation

SQL vs NoSQL vs key-value

Pick by consistency needs and access patterns β€” not by hype.

SQL document and key-value comparison
Default: Postgres (or similar) for core entities; Redis for hot session/rate-limit state.
  • SQL - strong consistency, joins, constraints, reporting
  • Document NoSQL - evolving JSON blobs, event-like records
  • Key-value - sessions, locks, idempotency keys, short TTL
  • Many apps use SQL + Redis together
  • Do not replace your OLTP DB with a vector DB

What agent backends store

Separate product entities from agent runtime data so ops stays clear.

Product data run state memory and audit stores
Product ACL lives in SQL even if chat transcripts are documents.
  • Product data - users, orgs, tickets, balances (SQL)
  • Run state - thread id, step index, checkpoints, HITL flags
  • Memory - summaries, preferences (SQL/docs; vectors later)
  • Audit - tool name, args hash, result status, tokens, cost
  • Idempotency keys - prevent duplicate writes on retry

Safe DB access from tools

Database tools are high risk. Prefer named operations over a generic query executor.

Parameterized queries authZ and transaction limits
Allowlisted tools beat query_database with free-form SQL from the model.
  • Parameterized queries / ORM β€” never string-concat SQL
  • Tenant and row-level authZ in the tool before mutate
  • Transactions for multi-row writes the agent intends as one unit
  • LIMIT / pagination β€” cap rows returned to the model
  • Least-privilege DB roles per service
  • Redact secrets from anything stored in transcripts

Schemas and migrations

  • Version product tables with migrations (Alembic, Prisma, etc.)
  • Store agent message payloads as JSON columns carefully β€” index what you query
  • Keep audit tables append-only when possible
  • Document retention: chats may need TTL or legal holds
  • Backup and restore drills matter before long-running agents ship

Concurrency and agent retries

  • Optimistic locking / version columns for contested rows
  • Idempotent upserts keyed by Idempotency-Key or tool call id
  • Avoid long open transactions during LLM waits
  • Use short DB transactions; do model calls outside them
  • Redis locks for β€œonly one agent run mutates X” when needed

Map to earlier modules

  • DB tools = Module 05 tool-use with higher blast radius
  • HTTP lesson: many tools call APIs that write to these DBs
  • Framework checkpoints (LangGraph) often need a store backend
  • Memory modules persist here before vector retrieval
  • Next: vector DBs for semantic search over chunks

Failure modes

  • Generic β€œrun any SQL” tools β†’ injection and data exfiltration
  • Putting secrets or PII into prompts then logging full rows
  • Holding DB transactions open across LLM latency
  • No tenant filters β€” agent reads another customer’s tickets
  • Using only a cache as the system of record

Program / implementation notes

Start with Postgres for product + run metadata, Redis for sessions/rate limits, and an append-only audit table. Expose get_ticket / update_ticket tools β€” not execute_sql.

  • Index foreign keys and (tenant_id, updated_at) for agent list tools
  • Next: Vector Databases for Agents (Pinecone, Chroma, FAISS, Weaviate)

Advantages and limitations

  • Advantage: durable memory and correct side effects
  • Advantage: SQL transactions protect money and tickets
  • Advantage: audit tables make agents debuggable
  • Limitation: over-normalizing chat blobs slows iteration
  • Limitation: NoSQL flexibility can hide missing constraints
  • Limitation: databases alone do not solve semantic search

Key points

  • SQL for transactional product truth; NoSQL/KV for flexible or hot state.
  • Persist runs, memory summaries, and immutable audit logs.
  • Allowlisted parameterized tools β€” never raw model SQL.
  • Enforce tenant authZ and row limits on every read/write.
  • Keep LLM calls outside long DB transactions.
  • Vector databases are complementary, not a replacement OLTP.

FAQs

Postgres or Mongo for agent chat history?

Either works. Postgres JSONB is enough for many apps and keeps joins with users/tickets. Mongo fits if documents are huge and rarely joined β€” still enforce tenant filters.

Where do embeddings live?

In a vector database or pgvector extension β€” covered next. Keep canonical chunks and metadata linked back to SQL ids.

Can the agent have a SQL REPL tool?

Avoid in production. If required for admins, gate with strong auth, read-only roles, allowlisted tables, and hard LIMIT β€” still risky.

SQL vs Redis for session memory?

Redis for short-lived session/rate-limit/lock state. Durable conversation and business records belong in SQL (or durable docs), not only a cache.

Interview questions

  1. When use SQL vs NoSQL for agent backends?

    Answer SQL for transactional entities, constraints, and joins; document/KV NoSQL for flexible payloads, caches, and short-lived session state β€” often combined.

  2. What should you persist for an agent run?

    Answer Run/thread identifiers, step or checkpoint state, tool-call audit (with cost/tokens), and any durable memory summaries β€” plus product mutations in the system of record.

  3. How do agents query databases safely?

    Answer Through allowlisted tools using parameterized queries/ORMs, tenant authZ, pagination limits, and least-privilege DB credentials β€” never model-authored SQL strings.

  4. Why avoid long transactions during LLM calls?

    Answer LLM latency holds locks and connection pools; do short DB transactions for writes, then call the model, then write again if needed.

  5. How do retries interact with DB writes?

    Answer Use idempotency keys or natural upsert keys so repeated tool calls from agent retries do not duplicate rows.

  6. Is a vector DB enough as the only database?

    Answer No. Vectors help retrieval; orders, permissions, and money still need a transactional store (usually SQL).

Related topics

Practice task

Complete each numbered practice step in a notebook or doc before opening the next lesson.

  1. Sketch tables/collections for users, tickets, agent_runs, and tool_audit.
  2. Define 3 allowlisted tools (e.g. get_ticket, list_open_tickets, add_comment) with authZ rules.
  3. Write the idempotency approach for add_comment under agent retries.
  4. List 4 fields you would never return raw into the LLM context from a ticket row.
  5. Answer interview questions 1, 2, and 3 in two sentences each.