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.

Intermediate 3 min readLesson 12 of 14

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

ModelData looks likeStrengthsExamples
Key-valuekey → opaque valueExtremely fast lookups, simple scalingRedis, DynamoDB, Memcached, etcd
DocumentJSON-like documents grouped in collectionsFlexible schema, natural mapping to objects, embedded dataMongoDB, Couchbase, Firestore
Wide-columnRows with a partition key and many sorted columnsMassive write throughput, linear scale-outCassandra, ScyllaDB, HBase, Bigtable
GraphNodes and relationships with propertiesMulti-hop relationship queriesNeo4j, Amazon Neptune
Time-seriesTimestamped measurementsIngestion rate, downsampling, retentionInfluxDB, TimescaleDB, Prometheus
SearchInverted indexes over textFull-text relevance, facets, logsElasticsearch, OpenSearch
VectorEmbedding vectorsSimilarity search for AIPinecone, Weaviate, Milvus, pgvector

Key-value: Redis

Python
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:

JSON
{
  "_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"
}
JavaScript
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.

SQL
-- 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.name

SQL vs NoSQL: how to choose

Choose relational (SQL) when…
  • 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
Consider NoSQL when…
  • 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.

Key takeaways
  • 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.