Summary#
NoSQL ("not only SQL") is a family of databases that drop parts of the relational model (fixed schemas, joins, multi-row transactions) to gain something specific: massive scale, flexible documents, very fast lookups, or a data model that fits the problem. The main types are key-value (Redis, DynamoDB), document (MongoDB), wide-column (Cassandra), graph (Neo4j), time-series (InfluxDB), search engines (Elasticsearch), vector databases (pgvector and others) and in-memory stores. Many follow BASE (basically available, soft state, eventually consistent) rather than strict ACID. Each type is excellent at a few access patterns and poor at others, so you design the data model around your queries.
Why It Exists#
In the 2000s, companies such as Amazon and Google hit limits of single-node relational databases: write volumes too high for one primary, data too large for one machine, and availability needs across data centres. Amazon's Dynamo paper (2007) and Google's Bigtable paper (2006) described systems that partition data across many cheap machines and relax consistency to stay available. Other NoSQL systems grew from different needs: flexible JSON documents for fast-changing apps, graphs for relationships, and text or vector search. This page builds on Relational Databases.
How It Works#
Key-value stores#
Data is a map from a key to an opaque value: GET user:42:session, PUT cart:42 {...}. The database does not look inside the value, so it can partition keys across many nodes and answer lookups in about a millisecond or less.
- Good at: lookups and writes by exact key at huge scale; sessions, carts, feature flags, caches, counters.
- Bad at: queries by anything other than the key, range scans (unless keys are ordered), joins and ad-hoc analysis.
- Examples: Redis (in memory), DynamoDB (managed, partition key plus optional sort key), Riak, etcd for small configuration data. See DynamoDB.
Key-value stores in depth#
Two families. Hash-based key-value stores (Memcached, Redis, DynamoDB partition keys) find a key by hashing it, so lookups are fast but there is no ordering: "all keys between A and C" is not a cheap query. Ordered key-value stores (RocksDB, LevelDB, FoundationDB, Bigtable, etcd, and DynamoDB within a partition by sort key) keep keys sorted, so range scans and prefix scans are efficient. Many higher-level databases are built on an ordered key-value engine underneath. CockroachDB and TiKV run on RocksDB-style engines, and MySQL's MyRocks uses RocksDB as an alternative storage engine.
The Dynamo design. Amazon's 2007 paper "Dynamo: Amazon's Highly Available Key-value Store" (DeCandia and colleagues, SOSP) combined several techniques that became the template for leaderless NoSQL:
- Consistent hashing with virtual nodes spreads keys across nodes and limits data movement when nodes join or leave. See Consistent Hashing.
- Replication to N nodes per key, with tunable read and write quorums R and W. With N = 3, W = 2 and R = 2, every read overlaps at least one node that saw the latest write, because R + W is greater than N.
- Sloppy quorums and hinted handoff: if a target replica is down, another node accepts the write with a "hint" and forwards it later, so writes keep succeeding during failures.
- Vector clocks to detect concurrent versions, with conflicts resolved by the application. The shopping cart merged conflicting carts, so an item added in one version was never lost, though a deleted item could occasionally reappear.
- Gossip for membership and Merkle trees for anti-entropy between replicas.
The paper's stated goal was that the cart must always accept writes, even during network partitions, which is the purest expression of the BASE philosophy described below. See Quorums and Leaderless Replication.
DynamoDB is not Dynamo. The managed service shares the name and some ideas but has a different design. Each partition is replicated across three availability zones by a leader-based Multi-Paxos group. Reads are eventually consistent by default and strongly consistent on request, at twice the cost. The data model is a partition key (hashed to choose a partition) plus an optional sort key (ordered within the partition). Queries such as "orders for user 42 in the last month, newest first" become one partition-key lookup with a sort-key range. Practical limits shape the model:
- Items are at most 400 KB.
- A single partition serves up to about 3,000 read units and 1,000 write units per second, where a write unit is one write of up to 1 KB per second. A hot key therefore caps out near 1,000 writes per second, though adaptive capacity helps spread uneven load.
- Global secondary indexes (GSIs) are separate, asynchronously updated copies of the data keyed differently. They make a second access pattern cheap, at the cost of extra write capacity and eventual consistency on the index.
Single-table design. Advanced DynamoDB users often store several entity types in one table with generic key names (PK = USER#42, SK = ORDER#2024-05-01#981), so that one query returns a user and their recent orders together, like a pre-joined result. It is powerful when access patterns are stable and painful when they change, which is the key-value trade-off in its sharpest form.
Modelling for key-value. The schema becomes flat. To answer several questions you duplicate data under several keys: user:42 for the profile, user_by_email:a@b.com -> 42 for login. This makes reads fast but means every change must update all copies, so consistency between them is the application's job. Key-value stores are therefore most often paired with a source of truth: SQL holds the canonical data, and a key-value cache in front serves the hot reads.
Coordination stores are key-value too. etcd, ZooKeeper and Consul store small amounts of critical data (configuration, leader election, service discovery) with strong consistency using consensus (Raft or ZAB). They handle thousands, not millions, of writes per second, and values are kept small (etcd's default request limit is about 1.5 MB). Do not use them as general databases.
Key-value with expiry as a coordination tool. A useful pattern is a key with a time to live (TTL) as a self-releasing lock or reservation. Suppose a ride-hailing service offers a ride to one driver at a time and gives them 10 seconds to accept. Tracking that timeout in a service's memory fails if the service restarts, because the "lock" is then never released, and a cleanup cron job adds delay and complexity. Writing SET ride:981:offer driver:17 NX PX 10000 to Redis instead creates the lock atomically only if none exists, and the store deletes it after 10 seconds on its own. The lock survives application crashes and needs no sweeper. See Distributed Locking.
Document stores#
Each record is a document, usually JSON or a binary form of it, with nested fields and arrays. Documents in one collection can have different fields, and you can index and query fields inside them.
{ "_id": "order_981", "user_id": 42, "status": "paid",
"items": [ { "sku": "A1", "qty": 2, "price_cents": 1999 } ],
"shipping": { "city": "Leeds", "postcode": "LS1 4AP" } }- Good at: data read and written as a whole unit (an order with its items, a product with varied attributes), fast-changing schemas, one round trip per entity.
- Bad at: many-to-many relationships and joins across collections; data duplicated across documents gets out of sync.
- Examples: MongoDB, Couchbase, Amazon DocumentDB; PostgreSQL's JSONB columns give similar flexibility inside a relational database.
Document stores in depth#
Modelling means choosing what to embed. A document database changes the central question from "how do I normalise this?" to "what belongs together in one document?". Take a small social app. In SQL you would have a users table and a posts table. In a document store you could embed each user's posts inside the user document:
{ "_id": "u42", "username": "maya", "email": "maya@example.com",
"posts": [ { "content": "Hello!", "created_at": "2024-01-01T10:00:00Z" },
{ "content": "Second post", "created_at": "2024-01-01T10:05:00Z" } ] }Reading a profile with its posts is now one lookup with no join. But posting means rewriting part of a growing document, the document grows without bound for a prolific user, and "the latest posts from everyone I follow" requires scanning many user documents. The usual guidance:
| Embed when | Reference (store an ID) when |
|---|---|
| The child is read with the parent nearly every time | The child is often read on its own |
| The child has no meaning without the parent (order lines, addresses) | The child is shared by many parents (products, authors) |
| The set is small and bounded (a few to a few hundred items) | The set grows without limit (posts, comments, events) |
| Children change together with the parent | Children are updated independently and often |
Here, posts should live in their own collection with a user_id field and an index on (user_id, created_at). A user document might still embed a small preview, such as the last three posts, as deliberate denormalisation for the profile page.
Size limits enforce the rule. MongoDB documents are capped at 16 MB, Firestore documents at about 1 MiB and DynamoDB items at 400 KB. The real limit arrives sooner. Every read and every rewrite of a 2 MB document moves 2 MB, so a "comments array" that grows to thousands of entries becomes slow long before it hits the cap. The unbounded array is the most common document-model mistake.
Indexes and queries. Unlike pure key-value stores, document databases index fields inside documents: single-field, compound, multikey (one entry per array element, so you can query "orders containing SKU A1"), text, geospatial, TTL (auto-delete after a date) and partial indexes. A widely taught rule for MongoDB compound indexes is equality, sort, range (ESR): put fields tested for equality first, then the sort field, then range filters, so the index can serve the sort without an in-memory step. Aggregation pipelines provide grouping, filtering and a limited join ($lookup), which is useful but slower and less flexible than SQL joins at scale.
Scaling and consistency. MongoDB runs as replica sets: one primary and usually two secondaries, with automatic election on failure in roughly 10 seconds or less. It shards collections by a shard key into ranges (chunks), with query routers (mongos) and config servers tracking where each range lives. A good shard key has high cardinality, spreads writes, and appears in most queries, such as user_id. A monotonically increasing key such as a timestamp sends all new writes to the last range, unless it is hashed. Durability and freshness are chosen per operation with write concern (w: 1 or w: "majority") and read concern (local, majority, linearizable).
Schema-less is really schema-on-read. The database does not enforce a shape, but your code still expects one, so the schema lives in the application. Six months of fast iteration can leave documents in five shapes that every reader must handle. MongoDB's $jsonSchema validation and application-level schema versions ("schema_version": 3, migrated lazily on read) bring back some discipline.
An honest interview note. Interview problems usually come with a tight, fixed set of requirements, so "the schema will evolve rapidly" is rarely true there, and it is the strongest reason to pick a document store. Unless the interviewer stresses wildly varying record shapes (product catalogues with thousands of attribute types, user-defined forms, CMS content), a relational database, possibly with a JSONB column for the flexible part, is usually the more defensible choice. Real-world reasons to prefer a document database do exist: deeply nested data that would need many joins, entities whose records differ greatly in structure (one user with a long work history, another with nearly nothing), and teams that value the developer experience of storing objects as they appear in code.
Wide-column stores#
Data is grouped by a partition key, and inside each partition rows are sorted by a clustering key. Writes go to an append-only log-structured engine, so these systems absorb very high write rates and scale by adding nodes. (Despite the name, they are not column-oriented analytics stores.)
- Good at: huge write-heavy datasets with known access patterns: messages per conversation, events per device, timelines per user. Multi-region replication with tunable consistency.
- Bad at: ad-hoc queries, joins, secondary indexes on high-cardinality fields, frequent updates to the same row, and transactions.
- Examples: Apache Cassandra, ScyllaDB, Google Bigtable, HBase. See Cassandra.
-- Cassandra CQL: all messages of one chat stored together, newest first
CREATE TABLE messages (
chat_id uuid,
message_id timeuuid,
sender_id bigint,
body text,
PRIMARY KEY ((chat_id), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);Wide-column stores in depth#
Lineage. Google's "Bigtable: A Distributed Storage System for Structured Data" (Chang and colleagues, OSDI 2006) defined the model: a sparse, distributed, sorted map indexed by row key, column (grouped into column families) and timestamp. Tables split into ranges of row keys called tablets, served by tablet servers and stored as immutable SSTable files on a distributed file system. HBase is an open-source Bigtable. Cassandra, created at Facebook and open-sourced in 2008, combined Bigtable's data model and storage engine with Dynamo's leaderless, ring-based distribution.
The write path (LSM tree). Cassandra and its relatives are fast at writes because nothing is updated in place:
Every write is one sequential append plus an in-memory insert, so a node can absorb tens of thousands of writes per second, and a cluster scales roughly linearly by adding nodes. Reads may have to check the memtable and several SSTables. Bloom filters, compaction and caches keep that manageable. The details, and the trade-off against B-trees, are in Storage Engines.
Query-first modelling. In Cassandra you design one table per query. The partition key decides which nodes hold the data and must be given in every query. The clustering columns decide the sort order inside a partition. If the app needs "messages in a chat, newest first" and "messages sent by a user", that means two tables written on every send, because neither can be served efficiently from the other's layout. Duplication is the normal cost of fast, predictable reads.
Partition sizing. Partitions should stay bounded. A common guideline is to keep them well under about 100 MB and a few hundred thousand rows. A chat that lives for years would break that, so the partition key adds a time bucket: ((chat_id, month), message_id). Readers then fetch the current bucket and step back to earlier ones as the user scrolls. Picking the bucket size is a classic interview discussion: too small means many partitions per read, and too large means hot, huge partitions.
Deletes are writes. A delete writes a tombstone marker, which must survive long enough (gc_grace_seconds, 10 days by default) to propagate to every replica, or deleted data can "resurrect" from a replica that missed the delete. Workloads that delete heavily, such as queues built on Cassandra, accumulate tombstones that slow reads. This is a famous anti-pattern.
Consistency per query. With replication factor 3, writing and reading at QUORUM (2 of 3) gives read-your-writes for a key. LOCAL_QUORUM keeps that within one data centre for multi-region clusters. ONE is fastest, but may read stale data. Lightweight transactions (IF NOT EXISTS) provide compare-and-set through Paxos at several times the latency.
Worked case: an ad-click pipeline. A system receives 10,000 ad clicks per second and lets advertisers query clicks per ad per minute. A Cassandra-style store is a good fit for the raw events: append-only, write-heavy, keyed by ad and time. But it is poor at the query, "sum clicks for these 200 ads over the last 30 days grouped by device", because SSTables are optimised for fetching specific partitions, not for scanning and aggregating across millions of them. The standard answer adds a processing step. A batch job, for example Apache Spark every 5 minutes, reads the new events and aggregates them by ad and minute. At 10,000 per second, 5 minutes is 3 million events. At about 100 bytes each, that is roughly 300 MB per batch, small enough for one machine, but Spark gives room to grow. The job writes the results to an OLAP (analytics) database such as Redshift, Snowflake, BigQuery, ClickHouse or Apache Druid, whose columnar storage makes SUM and COUNT over millions of rows fast.
The drawbacks: data is always a few minutes stale, and a traffic spike makes the next batch bigger and slower, so it can overrun its interval and fall further behind just when advertisers care most. A queue in front of the event store absorbs write spikes but not the latency. Moving to stream processing removes both problems. See Batch vs Stream Processing.
Why not a time-series database for the aggregates? Time-series stores shine when the main question is "metric X over time range Y" with modest cardinality. Millions of ad IDs, sliced by device, country and campaign, form a high-cardinality, multi-dimensional workload that OLAP engines handle better. For a simple "clicks per ad over time" requirement, a time-series database would be a reasonable choice, as long as you can explain the trade-off.
Graph databases#
Data is stored as nodes (people, products) and edges (FOLLOWS, BOUGHT) with properties. Traversing an edge is a direct pointer hop rather than a join, so queries many hops deep stay fast.
- Good at: relationship-heavy queries: friends of friends, recommendation paths, fraud rings, network and dependency analysis, knowledge graphs.
- Bad at: bulk analytics over all data, very high write throughput, and sharding (graphs are hard to split without cutting many edges).
- Examples: Neo4j (Cypher language), Amazon Neptune, JanusGraph.
Graph databases in depth#
Why traversals are cheap. Native graph databases such as Neo4j use index-free adjacency: each node record points directly to its relationship records, which point to neighbouring nodes. Following an edge costs a pointer hop, independent of the total graph size. In a relational database the same hop is an index lookup on a join table, costing O(log n) each time. One hop is cheap either way. The difference compounds at three, four or five hops, where the number of paths explodes and each step multiplies the work.
Query languages. Property graphs (nodes and edges with key-value properties) are queried with Cypher (Neo4j, and the basis of the ISO GQL standard published in 2024) or Gremlin (Apache TinkerPop, used by JanusGraph and Neptune). RDF triple stores use SPARQL and suit linked-data and knowledge-graph work. A friends-of-friends recommendation in Cypher:
MATCH (me:User {id: 42})-[:FOLLOWS]->(:User)-[:FOLLOWS]->(suggested:User)
WHERE NOT (me)-[:FOLLOWS]->(suggested) AND suggested <> me
RETURN suggested.id, count(*) AS mutuals
ORDER BY mutuals DESC LIMIT 10;The same query in SQL needs a self-join of the follows table and an anti-join. That is perfectly doable for two hops with good indexes, and it becomes awkward for variable-depth paths, which need recursive common table expressions (WITH RECURSIVE).
Where graph databases genuinely win:
- fraud detection across shared devices, cards and addresses, where rings can be several hops long;
- knowledge graphs with many entity and relationship types;
- network and IT dependency analysis ("what breaks if this switch fails?");
- access-control graphs with nested groups;
- built-in graph algorithms such as shortest path, PageRank and community detection.
Why interviewers are sceptical. Graphs are hard to shard. Any partitioning cuts edges, so traversals cross machines, and most graph databases scale reads by replication rather than by spreading one graph over many writers. Operating them is also a specialised skill. Meanwhile the largest social graph in the world is served from MySQL. Facebook's TAO (Bronson and colleagues, USENIX ATC 2013) is a graph-shaped API of objects and associations, implemented as a huge distributed cache over sharded MySQL. Twitter's early follower graph store, FlockDB, was likewise built on MySQL. For social graphs whose queries are mostly one or two hops ("who do I follow?", "do I follow X?"), an adjacency table with indexes in both directions, plus caching, is usually the simpler answer. In an interview, propose a graph database only when the problem centres on deep or variable-length traversals, and say why a relational adjacency list would struggle.
Time-series databases#
Optimised for data points with a timestamp, such as metrics and sensor readings: append-heavy writes, queries over time ranges, downsampling, and automatic expiry of old data. They compress well because consecutive values are similar.
- Good at: monitoring metrics, IoT telemetry, financial ticks; "average CPU per host per minute for the last 6 hours".
- Bad at: updates to old points, general relational queries, and very high cardinality (millions of unique label combinations) in some engines.
- Examples: InfluxDB, TimescaleDB (Postgres extension), Prometheus (monitoring). See Time-Series Databases.
Time-series databases in depth#
The data model. A point has a measurement (cpu), tags that identify the series (host=web-17, region=eu-west), one or more fields with values (usage=0.72), and a timestamp. Each unique combination of measurement and tag values is one series. Cardinality is the number of series, and it explodes quickly. 10,000 hosts × 50 metrics × 4 regions is already 2 million series. Add a user_id tag and you may have hundreds of millions, which most time-series databases cannot index efficiently. The rule is to put bounded, low-cardinality identifiers in tags, and to put unbounded identifiers in fields or in a different system entirely.
Why they compress so well. Facebook's "Gorilla: A Fast, Scalable, In-Memory Time Series Database" (Pelkonen and colleagues, VLDB 2015) showed two tricks now used widely:
- Timestamps arriving at regular intervals are stored as a delta of deltas. If points arrive every 60 seconds, the delta of delta is 0 and fits in a single bit.
- Float values are XOR-ed with the previous value. Similar consecutive values share most bits, so only the few differing bits are stored.
The paper reports an average of about 1.37 bytes per point instead of 16 for a raw timestamp plus value. That roughly 12x reduction is why a single node can keep weeks of metrics in memory.
Built-in lifecycle. Time-series data loses value with age, so these systems treat that as a feature:
- retention policies drop raw data after, say, 15 days;
- downsampling or continuous aggregates keep 1-minute averages for 90 days and hourly ones for years;
- storage is partitioned by time, so dropping old data deletes whole files instead of millions of rows. TimescaleDB calls these partitions chunks of a "hypertable".
Queries are naturally "aggregate over a time window grouped by tag": avg(usage) by host over 5m.
Examples and how they differ.
- Prometheus pulls ("scrapes") metrics from services every 15-60 seconds, stores them locally, and is the standard for Kubernetes monitoring. Long-term, multi-cluster storage is added with Thanos, Cortex or Mimir.
- InfluxDB accepts pushed points over HTTP and has its own query languages.
- TimescaleDB is a PostgreSQL extension, so you keep SQL, joins and the Postgres ecosystem.
As the ad-click example showed, a time-series database is the right tool for metrics-style queries with modest cardinality, and an OLAP engine is better for high-cardinality, multi-dimensional slicing. Details in Time-Series Databases.
Search engines#
Built on an inverted index: a map from each word to the documents that contain it, plus relevance scoring. They support full-text search, fuzzy matching, filters, facets and aggregations.
- Good at: text search with ranking, log search, product search with facets, autocomplete.
- Bad at: being the primary source of truth (usually near-real-time, roughly one second until a write is searchable), transactions, frequent updates of the same document.
- Examples: Elasticsearch, OpenSearch, Apache Solr. Usually fed from the main database by change data capture. See Elasticsearch.
Search engines in depth#
Why the main database is not enough. Without a search engine, finding events that mention "taylor swift" means something like SELECT * FROM events WHERE description LIKE '%taylor swift%'. A pattern with a leading wildcard cannot use a normal B-tree index, so the database scans and tests every row. On 10 million rows that can take seconds, and it still cannot rank results by relevance, match "swifts" to "swift", or forgive "tayler".
How an inverted index is built. Each document goes through an analysis pipeline:
- Tokenisation splits text into terms: "Taylor Swift: The Eras Tour" becomes
taylor,swift,the,eras,tour. - Normalisation lowercases terms and folds accents ("café" becomes "cafe").
- Stop words such as "the" may be removed.
- Stemming or lemmatisation reduces words to a root, so "running", "runs" and "ran" can match "run".
The index then maps each term to a posting list: the sorted IDs of documents containing it, often with positions for phrase queries. In simplified form:
{ "swift": [12, 87, 431],
"taylor": [12, 431, 902],
"tour": [12, 55, 431] }A query for "taylor swift tour" intersects or merges these lists, which is fast because they are sorted and compressed, then scores each match. The standard scoring function is BM25: a term counts more when it appears often in the document but rarely across all documents, adjusted for document length. Engines add boosts, for example popularity or recency.
Fuzzy search tolerates typos by matching terms within a small edit distance: the number of single-letter insertions, deletions or substitutions needed to turn one word into another. "Tayler" is one substitution from "taylor". Lucene implements this efficiently with automata over the term dictionary, so it does not compare the query against every term. Autocomplete uses prefix structures (finite-state transducers) or n-gram indexes.
Inside Elasticsearch and OpenSearch. Both are distributed layers over Apache Lucene:
- An index is split into shards, each a Lucene index with replicas on other nodes. Queries fan out to all relevant shards and the results are merged.
- New documents are written to an in-memory buffer and become searchable at the next refresh, every 1 second by default. This is why search is near real-time.
- A translog provides durability between flushes. Lucene writes immutable segments and merges them in the background, much like LSM compaction.
Keeping search in sync with the source of truth. A ticketing site keeps events and venues in PostgreSQL and serves search from Elasticsearch. Writing to both from the application risks one write succeeding and the other failing. The robust approach is change data capture: a connector such as Debezium reads the Postgres WAL and streams every insert, update and delete through Kafka into the search index, usually within seconds.
The costs are real. Someone must monitor the pipeline, replay it after failures, rebuild the index after a mapping change, and accept a seconds-long window when search results trail the database. A cluster of several nodes also adds noticeable infrastructure cost. See Change Data Capture and Elasticsearch.
Lighter options. PostgreSQL's built-in full-text search (tsvector columns with a GIN index, plus the pg_trgm extension for fuzzy and LIKE matching) handles millions of documents well and avoids a second system. It is often the right first step. Redis also offers a search module, but it is less mature than Lucene-based engines for serious relevance work. Move to a dedicated engine when you need advanced relevance tuning, facets across large datasets, or very high query volumes.
Vector databases#
Store embeddings: arrays of hundreds or thousands of numbers produced by machine-learning models, where similar items have nearby vectors. They answer "find the 10 nearest vectors to this one" with approximate nearest neighbour indexes such as HNSW, in milliseconds over millions of vectors.
- Good at: semantic search, recommendations, image similarity, retrieval for LLM applications (RAG).
- Bad at: exact queries and filters on their own (most combine vector and metadata filters), and they trade some recall for speed.
- Examples: pgvector (Postgres extension), Pinecone, Weaviate, Milvus, Qdrant; Elasticsearch and OpenSearch also support vectors. See Vector Databases.
Vector databases in depth#
What is being searched. An embedding model maps an item, such as a sentence, an image or a product, to a vector of typically 384 to 3,072 floating-point numbers, arranged so that similar items lie close together. Closeness is measured by cosine similarity (the angle between vectors), dot product, or Euclidean (L2) distance. "Find documents about refund policies" becomes "find the stored vectors nearest to the query's vector", which catches paraphrases that share no keywords.
Why exact search does not scale. Exact nearest neighbours means comparing the query against every vector. With 10 million vectors of 768 dimensions, one query needs about 7.7 billion multiply-adds and touches about 30 GB of float32 data (10M × 768 × 4 bytes). That is too slow for interactive use at any real query rate. Approximate nearest neighbour (ANN) indexes trade a little recall for orders-of-magnitude speed:
- HNSW (Hierarchical Navigable Small World graphs, Malkov and Yashunin, published in IEEE TPAMI in 2018) builds layered proximity graphs. A query starts in the sparse top layer and greedily walks closer, dropping down layers. It typically gives 95-99% recall in a few milliseconds. The cost is memory, because the graph links add to the vectors, and slow index builds.
- IVF (inverted file) clusters vectors around centroids with k-means and searches only the few nearest clusters (the
nprobesetting). It is cheaper to build and smaller, but recall depends on the probe count. - Product quantisation (PQ) compresses each vector into a few bytes by quantising sub-vectors. It is often combined with IVF to fit billions of vectors in memory, at some cost in accuracy.
Filtering is the hard part in practice. Real queries are "similar products in stock and under 50 dollars". Filtering after the ANN search can return too few results. Filtering before it can break the graph walk. Engines handle this with filtered HNSW traversal or by partitioning on common filters. Check this behaviour before choosing a product.
Hybrid search usually wins. Pure vector search can miss exact matches such as product codes, error messages or names, while keyword search misses paraphrases. Many production systems run both, a BM25 query and a vector query, and merge the ranked lists, for example with reciprocal rank fusion. Retrieval for LLM applications (RAG) commonly works this way.
Choosing. pgvector adds a vector type with HNSW and IVFFlat indexes to PostgreSQL. It keeps embeddings next to their relational data, in transactions, and is a strong default up to tens of millions of vectors. Dedicated engines (Pinecone, Milvus, Qdrant, Weaviate) add horizontal scale, quantisation, hybrid keyword-plus-vector ranking and managed operations for larger corpora. Elasticsearch and OpenSearch also offer kNN search, useful when you already run them. Memory sizing is the first estimate to make: 50 million 1,024-dimension float32 vectors take about 200 GB before index overhead, which decides between one large machine, quantisation and a sharded cluster. See Vector Databases.
In-memory databases#
Keep the whole dataset in RAM for sub-millisecond latency, with optional persistence (snapshots, append-only logs) and replication.
- Good at: caching, leaderboards (sorted sets), rate-limit counters, session stores, pub/sub, short-lived data.
- Bad at: datasets bigger than memory (cost), and durability: with asynchronous persistence, a crash can lose the last writes.
- Examples: Redis, Valkey, Memcached (pure cache, no persistence), and SAP HANA or VoltDB on the relational side. See Redis.
In-memory databases in depth#
Why RAM changes everything. A main-memory access takes about 100 nanoseconds, while a random read from an NVMe SSD takes about 100 microseconds, roughly a thousand times longer. A store that never touches disk on the request path can answer in well under a millisecond, with most of that time spent on the network. A single Redis instance commonly serves on the order of 100,000 or more simple operations per second, and pipelining or clustering pushes far beyond.
Redis's design choices. Redis executes commands on a single main thread, using an event loop. Every command is therefore atomic with no locks, but one slow command (KEYS * on millions of keys, a huge SMEMBERS, a long Lua script) blocks everyone. Newer versions use extra threads for network I/O, but command execution stays serial. The value of Redis is its data structures, each matching a common need:
| Structure | Typical use |
|---|---|
String with INCR and TTL | Counters, rate limits, simple cache entries, locks |
| Hash | Object fields such as a session or a user profile |
| List | Simple queues, recent-items lists |
| Set | Unique visitors, tags, membership checks |
| Sorted set | Leaderboards, priority queues, time-ordered feeds |
| Stream | Append-only log with consumer groups |
| Geo (on sorted sets) | Nearby search by radius |
| HyperLogLog | Approximate distinct counts in 12 KB |
Persistence and its gaps. Redis offers RDB snapshots (a forked child writes the whole dataset periodically) and an append-only file (AOF) that logs every write. With the common appendfsync everysec setting, a crash can lose about one second of writes. Replication to replicas is asynchronous, so a failover can drop acknowledged writes. Redis is therefore excellent as a cache, a coordination aid or a store for rebuildable data, and it should be used with care as the only copy of important data. Amazon MemoryDB adds a durable multi-AZ transaction log for teams that want Redis semantics with stronger durability.
Scaling out. Redis Cluster splits the key space into 16,384 hash slots spread across primaries, each with replicas. Multi-key operations work only when all the keys share a slot, which hash tags such as {user42}:cart and {user42}:profile guarantee. Memcached is simpler: a multithreaded, memory-only cache with no persistence or replication, sharded by the client. It is excellent for plain caching at very high throughput. Valkey is an open-source fork of Redis, started under the Linux Foundation in 2024 after Redis changed its licence, and it is now offered by several cloud providers.
In-memory geospatial and real-time state. Location updates from many drivers are a classic case. Writing every update to a disk-based database is wasteful when only the latest position matters and positions change every few seconds. One option is to batch updates and write them periodically to a database with a spatial index. PostgreSQL with the PostGIS extension, or a database using quadtrees or geohashes, can answer "drivers within 2 km". Batching cuts write volume but leaves positions seconds stale, which can produce poor matches. Keeping current positions in an in-memory geo index (Redis GEOADD and GEOSEARCH), with expiry for drivers who go silent, gives fresh answers at high update rates. See Geospatial Indexing.
Summary of NoSQL types#
| Type | Data model | Strength | Weakness | Examples |
|---|---|---|---|---|
| Key-value | Key to value | Fast lookups at any scale | Only query by key | Redis, DynamoDB |
| Document | JSON documents | Flexible schema, whole-entity reads | Joins, duplicated data | MongoDB, Couchbase |
| Wide-column | Partition + sorted rows | Huge write throughput, multi-region | Ad-hoc queries, transactions | Cassandra, Bigtable |
| Graph | Nodes and edges | Deep relationship traversals | Sharding, bulk analytics | Neo4j, Neptune |
| Time-series | Timestamped points | Time-range queries, compression | Updates, high cardinality | InfluxDB, TimescaleDB |
| Search | Inverted index | Full-text relevance, facets | Not a source of truth | Elasticsearch, OpenSearch |
| Vector | Embeddings | Similarity search | Approximate, needs filters | pgvector, Pinecone |
| In-memory | Structures in RAM | Sub-ms latency | Cost, durability | Redis, Memcached |
BASE#
Many distributed NoSQL systems describe themselves with BASE, a deliberate contrast to ACID:
- Basically available: the system answers requests even during failures, possibly with stale data.
- Soft state: replicas may hold different values for a while; state can change without new input as replicas sync.
- Eventually consistent: if writes stop, all replicas converge to the same value.
BASE is a choice to favour availability and latency over immediate consistency, in line with the CAP and PACELC trade-offs. See CAP Theorem and PACELC. The line has blurred: MongoDB supports multi-document ACID transactions, DynamoDB offers strongly consistent reads and transactions, and Cassandra lets you choose consistency per query (QUORUM, ONE).
BASE and eventual consistency in depth#
Where the term comes from. Eric Brewer and colleagues used "BASE" around 2000 to describe the design style of large web services, alongside the CAP conjecture. Dan Pritchett's 2008 ACM Queue article "BASE: An Acid Alternative" made it popular, describing how eBay split work across databases and accepted temporary inconsistency, reconciled with queues and idempotent updates. The acronym is a deliberate pun on ACID (base versus acid). Its letters are loose compared with ACID's, and they describe an attitude more than a formal guarantee.
What "eventually" actually involves. A leaderless store converges using three mechanisms:
- Read repair: when a quorum read sees replicas disagree, it returns the newest value and writes it back to the stale replicas.
- Hinted handoff: writes intended for a down node are held by another node and delivered when it returns.
- Anti-entropy: background processes compare replicas, often with Merkle trees, so only differing ranges are exchanged.
How long "eventually" takes is measurable: usually milliseconds within a data centre and up to hundreds of milliseconds across regions, but it can stretch to minutes or hours when a node has been down. Treat it as a distribution to monitor, not a constant.
Conflicts are the hard part. When two clients update the same key on different replicas concurrently, the system needs a rule. Last write wins (LWW) by timestamp is simple, but it silently drops one update, and clock skew can make it drop the newer one. Vector clocks or version vectors detect concurrency and return both versions to the application to merge, as the Dynamo shopping cart did. CRDTs (conflict-free replicated data types), such as counters, sets and registers designed to merge deterministically, give automatic convergence for specific data types. Riak and Redis Enterprise's active-active mode use them.
BASE is a per-operation choice today. Most modern NoSQL systems let you pick per request:
| System | Weak, fast option | Strong option |
|---|---|---|
| DynamoDB | Eventually consistent read (half the cost) | Strongly consistent read, transactions |
| Cassandra | ONE | QUORUM or LOCAL_QUORUM, lightweight transactions |
| MongoDB | readConcern: local, w: 1 | majority or linearizable, w: majority |
| Cosmos DB | Eventual, consistent prefix | Session, bounded staleness, strong |
The sound approach is to decide per data item what staleness costs. A like count off by a few for a second costs nothing. An account balance or an inventory count at checkout must be strongly consistent.
When to Use It#
- Key-value: you always know the key; you need single-digit-millisecond latency at very large scale.
- Document: entities are read and written as whole units and their shape varies or changes often.
- Wide-column: write-heavy data (100k+ writes per second) with access patterns known up front, often multi-region.
- Graph: the questions are about paths and relationships several hops deep.
- Time-series, search, vector: specialised workloads, usually alongside a primary database.
- In-memory: caches, counters and ephemeral data needing sub-millisecond reads.
When NOT to Use It#
- When you need flexible queries, joins and multi-row transactions on related data, and your scale fits a relational database.
- When access patterns are unknown; most NoSQL models punish queries you did not design for.
- When "NoSQL scales better" is the only reason; see SQL vs NoSQL.
How to Implement It#
- List access patterns first: every query, with its key, filters, sort order and expected rate.
- Pick the type whose model serves those patterns directly.
- Design keys so data spreads evenly (no hot partition) and each query reads one partition. See Data Modeling.
- Choose consistency per operation: strong where correctness matters, eventual where staleness is fine.
- Feed specialised stores (search, vector, analytics) from the source of truth with change data capture or streams.
| Technology | Fits when |
|---|---|
| DynamoDB | Serverless key-value/document at any scale, predictable access patterns |
| MongoDB | Document model with rich queries and secondary indexes |
| Cassandra / ScyllaDB | Write-heavy, multi-region, always-on |
| Neo4j | Graph traversals and graph algorithms |
| Elasticsearch / OpenSearch | Full-text and log search |
| pgvector | Vector search without a new database, up to tens of millions of vectors |
DynamoDB, Cassandra or MongoDB?#
These three are the NoSQL databases most often named in design discussions, and they overlap enough to confuse people.
DynamoDB is the choice when you are on AWS and want no servers to manage. It is fully managed, scales from zero to millions of requests per second, offers single-digit-millisecond latency at any size, and includes transactions, streams (a change feed that can trigger Lambda functions), TTL expiry and global tables. The constraints are the 400 KB item size, the need to plan access patterns and indexes up front, per-partition throughput limits, and lock-in to one cloud. It is a strong default for key-based workloads such as carts, sessions, user settings, device state and order lookups.
Cassandra (or its C++ reimplementation ScyllaDB) is the choice for very write-heavy, always-on workloads, especially across several data centres or clouds, when you are prepared to operate it. Its append-only LSM storage absorbs huge write rates, and its leaderless design has no failover pause. The costs: query-first modelling with duplicated tables, tombstone and compaction tuning, limited secondary indexing, no joins, and significant operational expertise, though managed offerings such as Amazon Keyspaces, Astra and ScyllaDB Cloud reduce it.
MongoDB is the choice when the document model itself is the attraction: rich nested entities, varied shapes, and a query language with secondary indexes, aggregations and geospatial support, while still sharding horizontally. It offers the richest ad hoc querying of the three and multi-document transactions. It is weaker than Cassandra for extreme write throughput across regions, and less hands-off than DynamoDB unless you use its managed Atlas service.
A compact way to say it in an interview: "DynamoDB if we want managed key-value at any scale on AWS, Cassandra if writes are enormous and multi-region with known queries, MongoDB if we need flexible documents with real secondary queries." Then name the access pattern that decides it.
A worked example: one product, several stores#
Consider an online marketplace with 20 million users and a peak of 5,000 orders per minute. Its data does not all want the same database:
| Data | Access pattern | Store | Why |
|---|---|---|---|
| Users, orders, payments | Transactions, constraints, support queries | PostgreSQL | Invariants across entities, about 100 writes per second at peak |
| Sessions and carts | Lookup by session or user ID, TTL | Redis | Sub-millisecond reads, data can expire |
| Product catalogue | Whole-product reads, attributes vary by category | MongoDB, or Postgres JSONB | Flexible shape, read as a unit |
| Product search | Text, typos, facets, ranking | Elasticsearch | Inverted index and BM25, fed by CDC |
| Click and view events | Very high write rate, read by user and time | Cassandra, or Kafka into a warehouse | Append-only, around 50,000 events per second |
| Recommendations | "Similar products" | pgvector or a vector database | Nearest-neighbour search over embeddings |
| Service metrics | Time-range aggregates | Prometheus | Built-in retention and downsampling |
Two lessons follow. First, the source of truth is clear for each fact. Product search results come from a derived index, and if the index is lost it is rebuilt from PostgreSQL or MongoDB. Second, every extra store has a cost: a sync pipeline, monitoring, backups, security controls and on-call knowledge. A startup might begin with PostgreSQL plus Redis for all of this, using JSONB, tsvector and pgvector, and split out a specialised store only when one workload outgrows it. That progression is a strong thing to describe in an interview.
Operating NoSQL systems in production#
Capacity and cost. Managed services price by usage. DynamoDB offers on-demand mode, which bills per request and suits spiky or unknown traffic, and provisioned mode with autoscaling, which is cheaper for steady load. A table doing 2,000 writes per second around the clock costs meaningfully more on demand than provisioned, so teams often start on demand and switch once traffic is understood. For self-hosted Cassandra or MongoDB, plan disk for replication factor × data × compaction headroom. Size-tiered compaction can temporarily need up to about double the space of the data being compacted.
Repair and backups. Leaderless stores need regular anti-entropy repair. In Cassandra, every node should complete a repair within gc_grace_seconds so tombstones reach all replicas before they are purged. Tools such as Cassandra Reaper schedule repairs. Backups use snapshots (hard links to immutable SSTables, which are cheap) plus incremental copies to object storage. Managed services offer point-in-time recovery: DynamoDB PITR covers the last 35 days. As with relational databases, test restores regularly.
What to monitor.
- p99 latency per operation, not just averages;
- per-partition or per-key heat, to catch hot partitions early;
- throttled requests (DynamoDB) or dropped mutations (Cassandra);
- compaction backlog and pending tasks;
- tombstones scanned per read;
- replica lag and failover events;
- for Redis, memory use against
maxmemory, the eviction rate and slow-log entries.
Changing the data model. Adding an access pattern later usually means a new table or index plus a backfill. Write new data to both shapes (dual-write, or a CDC consumer that maintains the new table), backfill historical data in throttled batches, verify counts and samples, switch readers, then retire the old shape. This is routine but takes days or weeks on large datasets. That is the real meaning of "NoSQL punishes queries you did not plan for".
Multi-region. Cassandra replicates across data centres natively, and LOCAL_QUORUM keeps latency regional. DynamoDB Global Tables replicate tables across regions with multi-active writes resolved by last-writer-wins, and they later added a strongly consistent multi-region option. MongoDB places replica set members in several regions and can use zone sharding to pin users' data to their home region. In all cases, decide which data may be written in more than one region at once, because that is where conflicts come from. See Multi-Region Data.
Trade-offs#
| Gain | Cost |
|---|---|
| Horizontal scale and high availability built in | Weaker or tunable consistency; fewer transactions |
| Data model matched to the workload | Poor at queries you did not design for |
| Flexible schemas | Schema rules move into application code |
| Very low latency for key access | Joins and aggregations done in the app or elsewhere |
| Predictable latency for designed queries | Each new query may need a new table or index and a backfill |
| Purpose-built engines for search, time series and vectors | More systems to sync, secure and operate |
Common Pitfalls#
- Choosing MongoDB or Cassandra and then needing joins everywhere.
- Partition keys with skew (one celebrity, one big tenant) that create hot partitions.
- Using a search engine as the only copy of the data.
- Assuming eventual consistency is "a few milliseconds" without measuring replica lag.
- Unbounded arrays inside documents that grow until reads and writes slow down.
- Delete-heavy workloads on Cassandra that pile up tombstones.
- Putting unbounded IDs such as user or request IDs in time-series tags, exploding cardinality.
- Running
KEYS *or other O(n) commands on a production Redis, blocking its single thread.
Real-World Examples#
Amazon's 2007 Dynamo paper described a highly available key-value store built for the shopping cart, and its ideas shaped Cassandra, Riak and later DynamoDB.
Discord has publicly described storing billions of chat messages in Cassandra, partitioned by channel and time bucket, and later migrating that workload to ScyllaDB.
Facebook serves its social graph through TAO, a graph-shaped cache over sharded MySQL, rather than a native graph database. Its Gorilla in-memory time-series store showed that compression to under 2 bytes per point makes keeping recent metrics in RAM practical. Elasticsearch powers search at many companies, typically fed from a relational source of truth.
In the Interview#
Talking about NoSQL in interviews#
The biggest mistake is choosing a category by name ("I'll use NoSQL because it scales"). Each NoSQL database has specific features, and the interviewer wants to hear how those features serve the access pattern. Relational databases can also scale horizontally with the right architecture, and they support flexible JSON columns. A NoSQL choice is justified only by something specific: a partition-key access pattern that needs no joins, a write rate beyond one primary, multi-region active-active writes, or a data model (documents, graphs, vectors, text) that fits the problem better.
A good script:
- "The dominant query is X, keyed by Y, at Z per second."
- "DynamoDB or Cassandra serves that as a single-partition read. The partition key is Y, the sort key is time, and partitions stay bounded through bucketing."
- "The cost is no ad hoc queries, so analytics and search go to separate stores fed by CDC."
- "For consistency I'll use strong reads only where needed, such as payments or inventory at checkout, and eventual reads elsewhere."
Typical follow-ups:
- "How do you avoid hot partitions?" Use a high-cardinality key. Add a suffix or bucket for known hot keys, and cache hot reads.
- "What happens on a node failure?" Replication factor 3 plus quorum operations keeps serving. Hinted handoff and repair restore the replica.
- "How do you add a new query later?" Add a new table or index fed from the same writes or from CDC, then backfill it. Accept that this is more work than adding a SQL index.
When most interviewers expect relational instead: user accounts, orders, payments, bookings, and anything with strong invariants across entities. A "polyglot" design is the norm in real systems: relational for the core, plus a cache, a search engine and possibly a wide-column store for one write-heavy stream.
Deep Dive: Multi-model databases and what really differsShow
The useful differences between databases are not "SQL vs NoSQL" but a few properties: data model (rows, documents, graphs), partitioning (single node vs automatic sharding), replication and consistency (leader-based vs leaderless, sync vs async), storage engine (B-tree vs LSM) and query capabilities (joins, secondary indexes, aggregations).
Many modern systems mix these. PostgreSQL handles JSON documents, full-text search, geospatial data (PostGIS) and vectors (pgvector). DynamoDB supports transactions. Distributed SQL databases (CockroachDB, Spanner) shard automatically like NoSQL while keeping SQL and serializable transactions. So ask "which properties do I need?" rather than "which category?". A common, sound architecture is one relational source of truth plus purpose-built stores (cache, search, analytics) fed from it.
Deep Dive: Two lineages, Dynamo and BigtableShow
Most of today's distributed NoSQL systems descend from two papers that made opposite choices.
Bigtable (Google, 2006): ordered ranges with a single owner. Rows are sorted by key and split into tablets, and each tablet is served by exactly one server at a time. A master assigns tablets, and the Chubby lock service ensures there is only one owner. Strengths: range scans are natural, and each key has one authoritative server, so single-row operations are strongly consistent without quorums. Weaknesses: when a tablet server fails, its tablets are briefly unavailable until reassigned, and sequential keys such as timestamps concentrate writes on one tablet, the classic hotspotting problem, solved by salting or reversing keys. Descendants: HBase, Google Cloud Bigtable, and the range-partitioned design of Spanner, CockroachDB and TiKV, which add consensus replication per range.
Dynamo (Amazon, 2007): hashed placement with no single owner. Keys are hashed onto a ring, any of N replicas can accept a write, and quorums plus repair produce convergence. Strengths: no failover pause, writes always accepted, and even distribution by design. Weaknesses: no efficient range scans across partitions, conflict resolution pushed to the application, and only tunable, not strict, consistency. Descendants: Cassandra (which borrows Bigtable's data model on top), Riak, ScyllaDB and Voldemort.
Why it matters for design. Ask two questions of any store. First, is data placed by hash (even load, no cross-key ranges) or by range (ordered scans, risk of hot ranges)? Second, does each key have one leader (simple strong consistency, failover pause) or many writers (always available, conflicts possible)? Those two answers predict most of a system's behaviour under load and failure, and they matter more than the label "NoSQL".
Key Takeaways#
- NoSQL types trade parts of the relational model for scale, flexibility or a better-fitting data model.
- Key-value and in-memory stores excel at lookups; document stores at whole entities; wide-column at write-heavy scale.
- Graph, time-series, search and vector databases serve specialised queries, usually alongside a primary database.
- BASE favours availability and eventual consistency; many systems now offer tunable or strong options.
- Model NoSQL data from access patterns first; queries you did not plan for are slow or impossible.
- Key-value stores split into hash-based (fast lookups) and ordered (range scans). DynamoDB models data as partition key plus sort key.
- Document models are about embed versus reference. Unbounded arrays are the classic mistake.
- Wide-column stores use LSM engines and query-first tables, with bounded partitions via time buckets.
- Search engines use inverted indexes, analysis and BM25, synced from the source of truth by CDC.
- Eventual consistency converges via read repair, hinted handoff and anti-entropy. Choose strong or weak per operation.