Database — NoSQL & SQL vs NoSQL¶
What is NoSQL?¶
NoSQL is a collection of data items represented as a key-value store, document store, wide column store, or graph database.
- Data is denormalized; joins are done in application code.
- Most NoSQL stores lack true ACID transactions and favor eventual consistency.
BASE (contrast with ACID)¶
BASE describes NoSQL properties and corresponds to choosing availability over consistency in the CAP theorem:
| Letter | Meaning |
|---|---|
| Basically available | The system guarantees availability. |
| Soft state | State may change over time, even without input. |
| Eventual consistency | The system becomes consistent over time (given no new input). |
Types of NoSQL databases¶
Key-Value Store¶
- Abstraction: hash table.
- O(1) reads/writes, often backed by memory or SSD.
- Keys can be kept in lexicographic order for efficient range retrieval.
-
High performance; used for simple data models or rapidly-changing data (e.g., in-memory cache layer).
-
Only a limited set of operations — extra complexity shifts to the app.
- Basis for document stores (and some graph databases).
- Examples: Redis, Memcached.
Document Store¶
- Abstraction: key-value store with documents (XML, JSON, binary) as values.
-
A document stores all info for a given object; query by the document's internal structure.
-
Documents can have completely different fields from one another.
- Examples: MongoDB, CouchDB; DynamoDB supports both KV and documents.
- High flexibility; good for occasionally-changing data.
Wide Column Store¶
-
Abstraction: nested map
ColumnFamily<RowKey, Columns<ColKey, Value, Timestamp>>. -
Basic unit is a column (name/value pair); columns group into column families (like a SQL table).
-
Access each column independently by row key; same row key = a row.
- Each value has a timestamp for versioning/conflict resolution.
-
Examples: Bigtable (Google, the first), HBase (open source, Hadoop ecosystem), Cassandra (Facebook).
-
High availability & scalability; good for very large datasets.
Graph Database¶
- Abstraction: graph.
- Each node is a record; each arc is a relationship between nodes.
- Optimized for complex relationships (many foreign keys / many-to-many).
- Example: social networks.
- Relatively new, fewer tools/resources; many are only accessible via REST APIs.
- Examples: Neo4j, FlockDB (Twitter).
Summary table¶
| Type | Abstraction | Examples | Best for |
|---|---|---|---|
| Key-value | Hash table | Redis, Memcached | Caches, simple/fast data |
| Document | KV + documents | MongoDB, CouchDB, DynamoDB | Flexible, semi-structured data |
| Wide column | Nested map | Bigtable, HBase, Cassandra | Very large datasets |
| Graph | Graph | Neo4j, FlockDB | Complex relationships |
SQL or NoSQL?¶
Choose SQL when¶
- Structured data
- Strict schema
- Relational data
- Need complex joins
- Need transactions (ACID)
- Clear patterns for scaling
- More established (developers, community, tools)
- Fast lookups by index
Choose NoSQL when¶
- Semi-structured data
- Dynamic/flexible schema
- Non-relational data
- No need for complex joins
- Storing many TB/PB of data
- Very data-intensive workloads
- Very high throughput for IOPS
Sample data well-suited to NoSQL¶
- Rapid ingest of clickstream/log data
- Leaderboard or scoring data
- Temporary data (e.g., shopping cart)
- Frequently accessed ("hot") tables
- Metadata / lookup tables
Key takeaways¶
-
ACID (SQL) prioritizes correctness/transactions; BASE (NoSQL) prioritizes availability/scale.
-
Pick the right NoSQL type for the data model, not just "NoSQL" generically.
- When in doubt: SQL for transactions and relations, NoSQL for scale and flexibility.
Common Interview Questions¶
Design a key-value store like Redis
Why it's asked here: a KV store is the foundational NoSQL type.
Key points to discuss:
- Hash-table abstraction, O(1) reads/writes, in-memory with optional persistence.
- Data structures (lists, sets, sorted sets) beyond plain strings.
- Eviction (LRU) and TTL for bounded memory.
- Consistency model (BASE/eventual) and why ACID isn't required.
flowchart LR
C[Client] --> K[KV store]
K -->|hash| N1[Node 1]
K -->|hash| N2[Node 2]
K -->|hash| N3[Node 3]
Design a social network's data structures
Why it's asked here: social graphs map naturally to a graph database.
Key points to discuss:
- Nodes = users, edges = relationships (follow, friend).
- Why a graph DB (Neo4j/FlockDB) beats relational joins for deep traversal.
- Traversal queries (friends-of-friends) and their performance.
- When to use adjacency lists vs a graph store.
flowchart LR
U[User node] -->|follows| F[Followed node]
U -->|friend| FR[Friend node]
G[Graph DB] --> U
G --> F
G --> FR
Design a recommendation system
Why it's asked here: recommendation data (user-item interactions) fits wide-column/ document stores.
Key points to discuss:
- Store user-item interaction history (wide-column, e.g., Cassandra).
- Document store for item metadata; KV for counters/lookups.
- Offline batch (MapReduce/Spark) vs online serving paths.
- BASE/eventual consistency for precomputed recommendations.
flowchart LR
E[User-item events] --> W[(Wide-column store)]
W -->|batch| B[MapReduce / Spark]
B --> R[(Recs store)]
R --> U[User]
Further reading¶
- Explanation of BASE terminology
- NoSQL databases: a survey and decision guidance
- Introduction to NoSQL
- SQL vs NoSQL differences
Full Design of a Redis-like Key-Value Store¶
A Redis-like key-value store is an in-memory data structure server that exposes low-latency operations over a simple protocol. To size the system, assume a workload of 100,000 operations per second at peak with a 90/10 read/write split. The typical value is small, so a 64 GB memory node can store tens of millions of keys if average key plus value overhead is around 256 bytes. Functional requirements include GET, SET, DEL, TTL/expiry, and richer data structures such as lists, sets, sorted sets, and hashes. Non-functional requirements are sub-millisecond p50 latency, high availability, bounded memory, and the ability to scale beyond a single node.
The high-level architecture uses one or more in-memory Redis processes behind a client-side cluster or proxy. A single Redis instance is an event-loop server that accepts many concurrent client connections and processes commands one at a time or with minimal blocking. For a distributed deployment, the keyspace is partitioned into hash slots across multiple primary shards; each primary copies data to one or more replica nodes. A cluster manager or sentinel monitors health and promotes a replica when a primary fails. Clients or a proxy route commands to the correct shard using the hash slot of the key.
The data model is the Redis hash table. Keys are binary-safe strings, and values are typed: strings, hashes, lists, sets, sorted sets, streams, etc. The in-memory hash table maps each key to a value object plus metadata such as TTL, LRU timestamp, and type. Persistence is optional and is implemented with periodic RDB snapshots and/or an append-only file that records each write so the dataset can be rebuilt after restart. Redis is chosen because the workload needs very high throughput and low latency on hot data, and the working set fits in memory; it does not provide SQL joins or multi-row transactions.
The core mechanism is the single-threaded command execution loop combined with efficient in-memory data structures and expiration/eviction. Because the working data is in RAM and commands are executed sequentially, there is no locking or latching overhead, and commands like GET, SET, and sorted set operations complete in microseconds. Time-based expiration is handled by a lazy check on access plus a periodic active expiration scan. When memory is full, Redis evicts keys according to a configurable policy such as allkeys-lru, volatile-ttl, or noeviction, so the system stays available under bounded memory. A simple RESP protocol makes parsing fast and language-independent.
Scaling and availability are achieved by sharding, replication, and failover. In Redis Cluster, the keyspace is divided into 16,384 hash slots, and each slot is assigned to a primary node. Adding a new node moves a subset of slots and their keys to it, spreading load and memory across machines. Each primary replicates asynchronously to at least one replica, so reads can be served from replicas and writes survive the loss of a primary if the replica is promoted quickly. Sentinel or the cluster manager performs leader election and client discovery. For higher availability, the design accepts that a replica may lag behind the primary and failover can lose writes that were not replicated before a crash.
The central trade-off is performance versus durability and consistency versus availability. Running entirely in memory gives microseconds-latency operations but means the dataset is limited by RAM and data can be lost if the process crashes before a snapshot or append-only file append is synced. An append-only file with every-write fsync improves durability but lowers write throughput; default Redis replication is asynchronous, so it favors availability and low latency over strong consistency. Sharding increases total capacity but makes multi-key operations and range scans harder because keys may live on different shards. Finally, allowing many data types and TTLs is convenient for applications but increases memory overhead and makes capacity planning less predictable.
flowchart LR
C[Client] --> P[Cluster Proxy / Smart Client]
P --> N1[Redis Primary Shard 1]
P --> N2[Redis Primary Shard 2]
N1 --> R1[Replica 1]
N2 --> R2[Replica 2]
S[Sentinel / Cluster Manager] --> N1
S --> N2
N1 --> D[(Persistence: RDB / AOF)]
N2 --> D
Design a Social Network's Data Structures¶
To design the data structures for a social network, first define the workload and the main entity types. Assume the network has about 500 million registered users, 200 million daily active users, and an average user participates in a few hundred relationships while following or friending a small fraction of that total. The functional requirements are to model users, profiles, posts or media, reactions, and the social graph, and to support common operations such as finding a user, fetching a profile, listing friends or followers, traversing friends-of-friends, and rendering a feed. The non-functional requirements are low latency for graph lookups, high availability, horizontal scalability, and efficient storage for a graph that is much larger than one machine can hold.
The high-level architecture separates the social graph from ordinary entity storage. User accounts, profiles, posts, and media metadata can live in a relational database because they are structured records with indexed lookups and transactional updates. The social graph itself is best served by a dedicated graph database or graph service, because the core operations involve many-to-many relationships and multi-hop traversal. Application servers act as the request layer and decide whether an operation needs the account database, the graph database, the post store, or a cache. A graph query such as friends-of-friends is sent to the graph service, which traverses relationship edges inside the graph store. A feed or profile read may instead use a cache that contains precomputed or hot results, reducing repeated graph traversal.
The core data model has users as nodes and relationships as directed or typed edges. A user node stores the user ID plus lightweight attributes such as name and profile metadata, while larger profile data can remain in the relational database or object storage. Edges represent relationship types such as friend, follow, block, or family, and may include created-at timestamps or visibility attributes. Posts are not usually stored as graph nodes; they belong in a sharded table or document store keyed by post ID, with the graph layer used to answer who may see that post. This design uses a graph database such as Neo4j or FlockDB for the relationship-heavy parts, but it does not force all social network data into one database. Relational tables work well for users and posts where uniqueness and transactions are important, while the graph store handles deep or many-to-many relationship queries that would require expensive recursive SQL joins.
The central mechanism for graph traversal is to follow edges from a starting user node with bounded depth and fan-out. For a friendship or follow query, the system loads the user node and navigates outgoing or incoming relationship edges. For friends-of-friends, it follows two edge hops and applies pagination, deduplication, and privacy filters. Very large fan-out users such as celebrities are handled through the graph structure but also need special feed logic so that enumerating millions of follower edges does not happen on every read. A social graph can be stored as an adjacency list, but a dedicated graph database improves deep traversal because it stores adjacent relationships on disk in the same locality as the node, and often supports query languages designed for variable-length paths. The application layer still owns access control and business rules rather than trying to push all of that into one graph query.
For scaling and availability, the graph is partitioned and replicated. Because relationships can cross shards, graph sharding must reduce expensive cross-machine hops. Common approaches are to shard users by user ID and store that user's outgoing relationships in the same shard, or to replicate edges so both endpoints keep copies for local traversal. Reads are then mostly local, while writes may update multiple shards asynchronously. User and post databases use read replicas and sharding by user or post ID. Hot user profiles, immediate friend lists, and feed caches live in Redis because they are read-heavy and can tolerate brief staleness. Object storage holds images and video, while the graph service stores only IDs and edge metadata. If a graph node fails, its replicas continue serving reads, and edge writes are queued so the failed node can catch up.
The main trade-offs are consistency versus latency and graph-store specialization versus operational simplicity. Replicating edges to both endpoint shards makes bidirectional traversal fast but can create temporary inconsistency after a follow or unfollow, which is usually acceptable in a social network. Using a dedicated graph database gives better traversal performance and a natural model for many-to-many relationships, but it adds another storage system to operate and can be less familiar than SQL. A pure relational adjacency list is simpler and supports joins, but multi-hop queries become slow and hard to scale as the graph grows. The design therefore separates strong transactional storage for accounts and posts from eventually consistent graph traversal and caching, accepting minor staleness in the social graph to keep reads fast and the system highly available.
flowchart LR
C[Client] --> LB[Load Balancer]
LB --> A[Stateless App Servers]
A --> U[(User/Post SQL DB or Document Store)]
A --> G[Graph Service]
G --> GD[(Graph DB: user nodes and relationship edges)]
A --> R[(Redis: profiles, friend lists, feed cache)]
A --> O[(Object Storage: media files)]
U <--> A
GD --> R
Design a Recommendation System¶
Assume the system serves about 100 million monthly active users, 50 million catalog items, and ingests roughly 500 million user-item interaction events per day. At peak it handles about 50,000 recommendation requests per second, and the online path must return a ranked list in less than 100 milliseconds. The functional requirements are to produce personalized item recommendations, to support related-item or recently-viewed item recommendations, and to incorporate signals such as clicks, purchases, ratings, and dwell time. The non-functional requirements are low online serving latency, high availability, horizontal scalability, and daily or near-real-time freshness for learned recommendations. Personalized rankings can be eventually consistent, but the raw interaction events must be durable and replayable.
The high-level architecture separates the offline training pipeline from the online serving path. Client interaction events are published through an API gateway to a durable event log such as Kafka. An offline batch layer, such as Spark or MapReduce, consumes these events to build user and item feature vectors and to train machine learning models. Trained model artifacts, user embeddings, item embeddings, and precomputed candidate sets are written to a model and feature store. During online serving, a stateless recommendation service receives the user ID and context, retrieves candidates from one or more recall stores, applies a ranking model to score those candidates, filters by business rules and inventory, and returns the top N items. Candidate generation is intentionally separated from ranking so the serving path never scans the full catalog.
The data model is split by access pattern. User-item interaction history is stored in a wide-column database such as Cassandra because it is append-heavy, very large, and must be partitioned by user ID or interaction key. Item metadata is stored in a document store because catalog items have flexible schemas and are read frequently during ranking and rendering. Precomputed recommendations, such as user-to-item top K lists and item-to-item similar lists, are stored in a key-value store for low-latency lookups. Embedding vectors and feature values may be kept in a specialized vector index or a low-latency feature store. Relational storage is not the primary store on the hot path because recommendation workloads require high-throughput scattered reads, not multi-row SQL joins.
The core mechanism is a two-stage recall and rank pipeline. For recall, collaborative filtering methods such as matrix factorization or alternating least squares learn latent factors for users and items, while item-based collaborative filtering computes similarity between item interaction vectors. More advanced systems may use a two-tower neural network trained on user features and item features to produce embeddings. Candidate retrieval can then be done with approximate nearest neighbor search over item embeddings or by fetching precomputed top K lists. Once candidates are retrieved, a lighter-to-medium complexity model such as logistic regression, gradient-boosted trees, or a neural ranker scores them using user context, item features, and interaction history. This recall-and-rank separation solves two problems at once: it keeps online latency low by reducing the candidate count before expensive scoring, and it allows the system to combine many candidate sources, such as collaborative, content-based, and popularity-based models. Cold-start users or items can be handled by falling back to global popularity, content similarity, or contextual rules until enough interaction data exists.
For scaling and availability, the online serving tier is stateless and runs behind a load balancer, so it can scale horizontally as request volume grows. Recommendation caches and recall stores are sharded by user or item ID and replicated to survive node failures. Kafka partitions allow the event stream to be replayed after crashes, which makes the offline pipeline recoverable. Model training jobs run on separate compute clusters and can be rescheduled if a worker fails. If a personalized recall store is unavailable, the serving service can fall back to cached global or category-level popular items, preserving availability at the cost of personalization. Batch precomputation reduces serving-time compute but introduces staleness, so hot recommendations may be refreshed more often than long-tail recommendations.
The main trade-offs are freshness versus cost, latency versus accuracy, and personalization versus availability. Precomputing recommendations in batch is cheap and fast to serve but can lag recent user behavior by hours or a day. Real-time streaming updates make recommendations fresher but add complexity and cost. Approximate nearest neighbor search dramatically reduces retrieval latency but can miss some high-quality candidates compared with exact nearest neighbor search. Using multiple recall sources improves coverage but increases infrastructure complexity. Finally, recommendation results are intentionally eventually consistent, so a user may see a recommendation that is a few minutes or hours behind their most recent interaction; this is acceptable for most consumer products because durability and availability of the event stream matter more than strong consistency on the recommendation list.
flowchart LR
U[User Request] --> G[API Gateway]
G --> S[Stateless Recommendation Service]
E[Interaction Events] --> G
G --> K[Kafka Event Log]
K --> SP[Spark or MapReduce Offline Jobs]
SP --> M[Model and Feature Store]
SP --> R[Recall Store]
M --> R
S --> R
S --> F[Ranking and Filtering]
F --> C[Hot Recommendation Cache]
F --> U
S --> D[(Wide-column Interaction Store)]
S --> I[(Document Item Metadata Store)]