SQL vs NoSQL
Choose relational vs document/key-value stores for AI app state and metadata.
In plain words
SQL databases keep data in neat tables that can be combined and checked carefully. NoSQL databases keep data in more flexible shapes that are fast for simple lookups and easy to spread over many machines.
Think of it like…
A filing cabinet with labelled folders versus a bag of index cards. The cabinet (SQL) enforces structure and lets you cross-reference folders; index cards (key-value or documents) let you find one card instantly by its label and scale by adding more bags, but cross-referencing is your problem.
Where you’ve seen it
An assistant platform has five kinds of state. Accounts, organisations, subscriptions and the credits ledger need relationships, constraints and multi-row transactions, so they live in PostgreSQL. Conversation messages are append-heavy and read as "the last 20 for conversation X": at 1,000,000 conversations × 20 messages × 1.5 KB the volume is 20,000,000 messages ≈ 30 GB, comfortably within one PostgreSQL instance using a table with an index on (conversation_id, created_at) and a jsonb column for variable tool-call payloads; a key-value design (partition key conversation_id, sort key timestamp, as in DynamoDB) would also fit and scale writes horizontally, but at 200 writes a second (100 requests × 2 messages) PostgreSQL has ample headroom. Traces and evaluation events are append-only, time-ordered and aggregated by tenant and day, so they go to a columnar analytics store or partitioned PostgreSQL tables with a retention policy. Sessions, rate-limit counters and semantic-cache entries are small, expire quickly and need sub-millisecond access, so they live in Redis. Embeddings start in PostgreSQL with pgvector to keep filtering, joins and transactions in one place, and move to a dedicated vector database only when recall or latency at scale demands it. The team writes down the thresholds that would trigger a change (sustained writes beyond what one primary handles, a hot-partition problem, a latency SLO the relational path can't meet) rather than adopting a second database speculatively. Limits are checked early: a DynamoDB item is capped at 400 KB and a MongoDB document at 16 MB, which matters for long transcripts stored as one record.
Words you’ll hear
- Access pattern
- The queries and writes an application actually performs, which should drive schema design.
- ACID
- Atomicity, consistency, isolation and durability guarantees for transactions.
- Eventual consistency
- A model where replicas converge over time rather than instantly.
- Polyglot persistence
- Using different stores for different kinds of data.
Visual diagram
Theory & deep dive
What each family is good at
Relational databases shine when data has relationships and integrity rules: users belong to organisations, subscriptions to plans, ledger entries to accounts. You get joins, constraints, foreign keys, indexes, transactions and a mature ecosystem. PostgreSQL's jsonb columns, GIN indexes and extensions (pgvector, full-text search) cover many semi-structured needs, and a single well-indexed primary handles tens of thousands of simple operations a second, which exceeds the needs of most AI applications for a long time. Key-value stores (Redis, DynamoDB) deliver very fast lookups by a known key and scale horizontally, ideal for sessions, counters, caches and idempotency records, but queries beyond the key need extra design.
Document stores keep self-contained JSON documents, convenient when a record is always read and written as a unit and its shape varies (tool-call payloads, agent state), with the trade-off of weaker joins and cross-document transactions. Wide-column stores handle enormous write-heavy tables partitioned by key, such as event streams, but require query-first modelling. Graph databases answer multi-hop relationship queries (knowledge graphs) that are awkward in SQL. NoSQL systems often relax consistency (eventual) in exchange for availability and scale; know which guarantees you are giving up before depending on them for money or permissions.
1,000,000 conversations × 20 messages = 20,000,000 rows × 1.5 KB ≈ 30 GB. At 100 requests/s × 2 messages = 200 inserts/s. One PostgreSQL primary with the (conversation_id, created_at) index serves "last 20 messages" in a few milliseconds; the volume and rate do not demand a distributed store yet.
Choosing: access patterns, consistency, scale and operations
Start from access patterns: list the ten most important reads and writes with their frequency and latency targets. If they need joins, ad hoc filters and reports (cost per tenant per day), SQL is the natural fit. If they are almost all "get or put by key" at very high rates, a key-value or wide-column design may be simpler. Ask about consistency: billing, quotas and permissions need transactions; a message timeline or cache can tolerate eventual consistency. Estimate scale: rows, growth per month, peak writes per second and item sizes; most products stay within a single relational primary for years, and read replicas, partitioning and caching extend that further.
Weigh operations: every extra datastore adds backups, upgrades, monitoring, access control, local development setup and on-call load, so a small team should favour one primary store plus Redis. Keep an escape hatch: access data through a repository layer, use stable IDs and keep events in a log so you can move a workload later (messages to DynamoDB, traces to a column store) without rewriting the application. Record the triggers for change, for instance sustained write rates above what one primary handles, hot partitions, or an SLO the relational path can't meet, and revisit when measurements, not fashion, cross them. Check limits early: DynamoDB items max out at 400 KB and MongoDB documents at 16 MB, which long transcripts or large tool outputs can hit.
Messages: PostgreSQL table, index (conversation_id, created_at), jsonb payload. Revisit if sustained writes exceed 5,000/s, p95 history read exceeds 50 ms after tuning, or storage passes 2 TB. Alternative considered: DynamoDB with conversation_id partition key and timestamp sort key.
How it works, step by step
Step 1 of 41. List workloads and access patterns
Write the top reads and writes, their rates, latency targets and consistency needs for each kind of state.
- Estimate
- rows and growth
When to use it & trade-offs
What it is
Relational (SQL) databases store data in tables with a fixed schema, relate them with keys, query them with joins and aggregates and guarantee ACID transactions. NoSQL covers several families: key-value stores (Redis, DynamoDB) for fast lookups by key, document stores (MongoDB, Firestore) for nested JSON records, wide-column stores (Cassandra) for huge write-heavy tables and graph databases for relationships. The choice follows from access patterns, consistency needs, data shape and scale, not fashion. AI applications have several kinds of state (accounts and billing, conversation history, traces, caches, embeddings) and rarely fit a single store perfectly, which is why PostgreSQL with JSON columns and extensions is the common starting point.
Why it matters: State decisions are expensive to reverse. Choosing a document store for billing leaves you hand-writing consistency; choosing a relational database for a billion-row event log forces premature sharding; choosing three databases for a ten-person team multiplies operations. A clear view of the workloads (what is read, written, joined and how fast it grows) lets you pick the simplest option that meets them and know the signals that justify adding another.
When to reach for it
- PostgreSQL for the transactional core of most AI apps
- Redis for sessions, rate limits and semantic caches
- Columnar stores for traces and eval analytics
When to avoid or be careful
- A document store for money and permissions
- Adding a datastore without a measured need
- Storing multi-megabyte transcripts as single records
Store families
Strengths: Transactions, joins, constraints, jsonb and extensions.
Watch out: Horizontal write scaling takes effort.
Strengths: Very fast and easy to scale.
Watch out: Limited query flexibility.
Strengths: Flexible schema; natural JSON.
Watch out: Weaker joins and cross-record transactions.
Strengths: Huge write throughput; fast aggregates.
Watch out: Query-first modelling; poor for OLTP.
Interview signals & numbers to know
When this topic comes up
- “SQL or NoSQL for chat history?”
- Access-pattern driven design
- ACID versus eventual consistency
- When Postgres jsonb is enough
- Cost of operating several databases
Benchmarks & rules of thumb
- ≈ 30 GB
- 20 million 1.5 KB messages
- 200 writes/s
- 100 requests/s × 2 messages each
- 400 KB / 16 MB
- DynamoDB item and MongoDB document size limits
Common mistakes & follow-ups
Common interview mistakes
- Choosing a store by popularity rather than access patterns.
- Using eventual consistency for balances.
- Underestimating the operational cost of a second database.
Likely interviewer follow-ups
- What would make you move messages out of PostgreSQL?
- How would you store variable tool-call payloads?
- Where does the vector index live in your design?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply SQL vs NoSQL with generative AI interview Q&A and hands-on practice.