{}DSA Atlas

NoSQL & Choosing a Database

Key-value, document, wide-column, graph, search, time-series and vector databases — data models, strengths, weaknesses, query-first modelling (Cassandra/DynamoDB single-table design), BASE, and a practical SQL-vs-NoSQL decision framework.

Intermediate7 interview questions

Why NoSQL exists

Relational databases were designed for a single machine with strong consistency. In the 2000s, web-scale companies needed:

  • horizontal scale across hundreds of machines (Bigtable 2006, Dynamo 2007);
  • high availability across data centres, even during network partitions;
  • flexible schemas for fast-changing products;
  • specialised access patterns (graphs, search, time series, caching).

"NoSQL" ("not only SQL") covers several very different families.

The families

FamilyData modelExamplesGreat atWeak at
Key-valuekey → opaque valueRedis/Valkey, DynamoDB, Memcached, etcd, RocksDBO(1) get/put, caching, sessions, countersqueries by value, relationships
Documentkey → JSON/BSON documentMongoDB, Couchbase, Firestore, DocumentDBnested aggregates, flexible schemamany-to-many joins, cross-document invariants
Wide-columnpartition → sorted rows → sparse columnsCassandra, ScyllaDB, HBase, Bigtablemassive writes, time-ordered data, multi-DCad-hoc queries, joins
Graphnodes + edges + propertiesNeo4j, Amazon Neptune, JanusGraphmulti-hop traversalsbulk aggregation, sharding
Searchinverted index over documentsElasticsearch, OpenSearch, Solr, Meilisearchfull-text, relevance, facets, logstransactions, being the source of truth
Time-series(series, timestamp) → valueTimescaleDB, InfluxDB, Prometheus, QuestDBingest, downsampling, time windowsarbitrary updates
Vectorid → embedding (+ metadata)pgvector, Pinecone, Milvus, Weaviate, Qdrantsimilarity search for AI/RAGexact lookups by attributes alone
NewSQL / distributed SQLrelational + horizontal scaleSpanner, CockroachDB, YugabyteDB, TiDBACID + scale-outlatency vs single node, cost

Key-value stores

Text
SET session:9f2c  "{user_id: 42, expires: ...}"  EX 3600
GET session:9f2c
INCR rate:user:42:2026-10-07T17:05
ZADD leaderboard 1520 "alice"      # sorted set
ZREVRANGE leaderboard 0 9 WITHSCORES

Redis (and its BSD-licensed fork Valkey, which several clouds ship by default after Redis's 2024 licence change) is more than a cache: strings, hashes, lists, sets, sorted sets (leaderboards, rate limiting), streams, pub/sub, geo, HyperLogLog, Bloom filters (module). Persistence via RDB snapshots and AOF logs; replication and Redis Cluster (16,384 hash slots) for scale.

Document stores

JSON
{
  "_id": "order_981",
  "customer": { "id": 42, "name": "Asha" },
  "items": [
    { "sku": "MOUSE-1", "qty": 2, "price_cents": 49900 },
    { "sku": "KB-7", "qty": 1, "price_cents": 129900 }
  ],
  "status": "paid",
  "created_at": "2026-10-07T10:21:00Z"
}

Embed vs reference

Embed whenReference when
read together, owned by the parentshared by many parents
bounded size (order lines)unbounded growth (all comments ever)
updated togetherupdated independently and often

Wide-column stores (Cassandra-style)

PRIMARY KEY ((sensor_id, day), ts) partition(s-17, 2026-10-07) → hashed to a token,stored on 3 replica nodes rows sorted by clustering key ts (DESC) ts=17:05:00 temp=21.4 humidity=40 ts=17:04:00 temp=21.3 ts=17:03:00 temp=21.3 humidity=41 a range query on ts inside one partition = one sequential read
The partition key spreads data across nodes; the clustering key sorts rows within a partition.
SQL
-- CQL: one table per query
CREATE TABLE readings_by_sensor_day (
  sensor_id text, day date, ts timestamp, temp double, humidity double,
  PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
  AND default_time_to_live = 7776000;      -- 90 days

SELECT * FROM readings_by_sensor_day
WHERE sensor_id = 's-17' AND day = '2026-10-07' AND ts > '2026-10-07 16:00';

Rules of thumb: model one table per query; partitions should stay under ~100 MB; avoid hot partitions; deletes create tombstones (many tombstones = slow reads); tune consistency per query (ONE, QUORUM, LOCAL_QUORUM).

DynamoDB single-table design

PKSKattributes
USER#42PROFILEname, email
USER#42ORDER#2026-10-07#981total, status
USER#42ORDER#2026-09-30#940total, status
ORDER#981ITEM#1sku, qty

Query(PK = "USER#42", SK begins_with "ORDER#") returns a user's orders, newest last, in one request. GSIs (global secondary indexes) add alternative access patterns (eventually consistent). Capacity is per partition (≈ 3,000 RCU / 1,000 WCU), so key design must spread load.

Graph databases

Text
// Cypher (Neo4j): friends-of-friends who like jazz, not already friends
MATCH (me:Person {id: 42})-[:FRIEND]->(:Person)-[:FRIEND]->(fof:Person)-[:LIKES]->(:Genre {name: 'Jazz'})
WHERE NOT (me)-[:FRIEND]->(fof) AND fof <> me
RETURN fof.name, count(*) AS mutual ORDER BY mutual DESC LIMIT 10;

Search engines

An inverted index maps each term → list of documents (postings) containing it, with positions and frequencies for ranking (BM25). Analysers tokenise, lowercase, stem ("running" → "run") and remove stop words. Used for product search, logs (ELK/OpenSearch), autocomplete, faceted navigation. Usually a secondary store fed from the primary database.

Vector databases

Store embeddings (e.g. 768–3072-dimension float vectors) and answer approximate nearest neighbour (ANN) queries with indexes like HNSW (graph-based) or IVF/PQ (clustering + quantisation). Core of semantic search and retrieval-augmented generation (RAG). Options range from pgvector inside Postgres (simple, transactional, good to tens of millions of vectors) to dedicated systems (Pinecone, Milvus, Qdrant, Weaviate) for larger scale and filtering. See AI systems.

Choosing a database: a decision framework

What are the access patterns? relational data, joins,multi-row transactions simple key lookups,huge scale / low latency full-text / relevance /similarity search time-ordered metrics,events, logs PostgreSQL / MySQL→ distributed SQL if onenode + replicas can't cope DynamoDBCassandra · Redis(cache, sessions) Elasticsearch,pgvector(as secondary indexes) TimescaleDB, Influx,ClickHouse, Kafka+ object storage Polyglot persistence: one system of record + specialised derived stores fed by CDC/events.
Start from queries and guarantees; most systems use several stores.

Questions to ask:

  1. What are the read and write patterns, and their ratios and volumes (QPS, data size, growth)?
  2. Do I need multi-entity transactions or strong consistency?
  3. Do I need ad-hoc queries and joins, or known key-based queries?
  4. What latency and availability targets (multi-region? survive a region outage?)
  5. How will the schema evolve?
  6. Operational cost: managed service available? Team expertise?

Interview questions

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.