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