NoSQL Databases
Key-value, document, wide-column, graph, time-series, search and vector databases — data models, strengths, trade-offs, and how to choose between SQL and NoSQL.
NoSQL ("not only SQL") is an umbrella for databases that don't use the classic relational model. They emerged in the late 2000s when web companies needed horizontal scale, flexible schemas and specialised data models. Today the line has blurred: relational databases handle JSON and scale out, and many NoSQL systems have added SQL-like queries and transactions.
The families
| Model | Data looks like | Strengths | Examples |
|---|---|---|---|
| Key-value | key → opaque value | Extremely fast lookups, simple scaling | Redis, DynamoDB, Memcached, etcd |
| Document | JSON-like documents grouped in collections | Flexible schema, natural mapping to objects, embedded data | MongoDB, Couchbase, Firestore |
| Wide-column | Rows with a partition key and many sorted columns | Massive write throughput, linear scale-out | Cassandra, ScyllaDB, HBase, Bigtable |
| Graph | Nodes and relationships with properties | Multi-hop relationship queries | Neo4j, Amazon Neptune |
| Time-series | Timestamped measurements | Ingestion rate, downsampling, retention | InfluxDB, TimescaleDB, Prometheus |
| Search | Inverted indexes over text | Full-text relevance, facets, logs | Elasticsearch, OpenSearch |
| Vector | Embedding vectors | Similarity search for AI | Pinecone, Weaviate, Milvus, pgvector |
Key-value: Redis
r.set("session:abc123", user_json, ex=3600) # expires in an hour
r.incr("page_views:2025-01-15") # atomic counter
r.zadd("leaderboard", {"ada": 3120}) # sorted set
r.zrevrange("leaderboard", 0, 9, withscores=True)Redis keeps data in memory with rich data types (strings, hashes, lists, sets, sorted sets, streams). It's used for caching, sessions, rate limiters, leaderboards, queues and locks. Persistence (snapshots, append-only file) and replication exist, but treat it as a primary database only with care.
Document: MongoDB
Store an aggregate — an order with its items and shipping address — as one document:
{
"_id": "ord_9f2",
"customer": { "id": "c_17", "name": "Ada" },
"items": [
{ "sku": "KB-1", "qty": 1, "price": 80 },
{ "sku": "MS-2", "qty": 2, "price": 25 }
],
"status": "shipped",
"createdAt": "2025-01-15T10:00:00Z"
}db.orders.find({ "customer.id": "c_17", status: "shipped" }).sort({ createdAt: -1 })
db.orders.createIndex({ "customer.id": 1, createdAt: -1 })Reading an order is one lookup with no joins. The trade-off: data that's shared across documents (the customer's name) is duplicated, and queries that cut across aggregates ("total sales per SKU") are harder. Model around your access patterns: embed what's read together; reference what's shared or unbounded.
Wide-column: Cassandra and DynamoDB
You design tables per query. The partition key decides which node stores the data; the clustering key sorts rows within a partition.
-- Cassandra CQL: "the latest messages in a chat"
CREATE TABLE messages (
chat_id uuid,
sent_at timeuuid,
sender text,
body text,
PRIMARY KEY ((chat_id), sent_at)
) WITH CLUSTERING ORDER BY (sent_at DESC);
SELECT * FROM messages WHERE chat_id = ? LIMIT 50;Queries must include the partition key; there are no joins, and secondary indexes are limited. In exchange, writes scale linearly across hundreds of nodes with no single point of failure. DynamoDB follows the same partition/sort key model as a fully managed service; single-table design packs several entity types into one table to serve all access patterns.
Graph databases
When the questions are about relationships — friends of friends, fraud rings, recommendations, dependency graphs — graph databases traverse edges directly instead of doing repeated joins:
// Cypher (Neo4j): people Ada's friends know who work at Acme
MATCH (a:Person {name: 'Ada'})-[:FRIEND]->(f)-[:FRIEND]->(fof)-[:WORKS_AT]->(:Company {name: 'Acme'})
WHERE fof <> a
RETURN DISTINCT fof.nameSQL vs NoSQL: how to choose
- Data is relational, with many entity types and relationships
- You need ad-hoc queries, reporting, joins
- Strong consistency and multi-row transactions matter (money, inventory)
- The schema is reasonably known
- Scale fits on one primary plus replicas — this covers most applications
- Access patterns are simple and known (key lookups, a few queries)
- Write volume or data size needs horizontal scale-out
- The data is naturally document-, graph-, time-series- or vector-shaped
- The schema varies a lot between records
- You need multi-region active-active writes
BASE and consistency
Many distributed NoSQL systems favour availability and partition tolerance and offer eventual consistency ("BASE": basically available, soft state, eventually consistent), often with tunable levels — Cassandra's QUORUM reads and writes, DynamoDB's strongly consistent reads. See CAP & PACELC and Replication.
- NoSQL covers key-value, document, wide-column, graph, time-series, search and vector databases.
- Document stores embed aggregates; model around access patterns.
- Wide-column stores scale writes horizontally; design tables per query and avoid hot partitions.
- Graph databases answer multi-hop relationship queries efficiently.
- Default to a relational database; add specialised stores for specific needs.