- Part 15 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
SQL vs. NoSQL Databases: From Data Modeling to Distributed Scaling
Learn the mechanical differences between relational and non-relational databases, how data models impact scaling, and how to select the right persistence layer.
MonksBit Desk
November 25, 2026 · 10 min read · 27 views
Read
A relational database organizes data into predefined tables with rows and columns enforced by a strict schema and linked by mathematical relations. A non-relational database stores data using flexible, non-tabular structures such as key-value pairs, nested documents, wide-column families, or graph networks without requiring uniform table schemas across entries.
You will need. Basic knowledge of data structures such as hash tables and trees · Familiarity with basic client-server web architecture
The full lesson
Level 1 · Beginner: Understanding structural tables versus flexible documents
At the simplest level, relational databases (often called SQL databases) store entities in flat tables. Each row corresponds to a single record, and each column corresponds to a typed attribute. For example, if you store a user, you define columns for id, name, and email. If a user has multiple phone numbers, you do not pack them into one cell. Instead, you create a separate table for phones with a reference linking back to the user id. This process of splitting data to remove duplication is called normalization.
Non-relational databases (often called NoSQL databases) reject the requirement of flat, uniform tables. The most common entry-level format is the document store. In a document store, all data related to an entity lives inside a single hierarchical record, typically formatted as JSON. If a user has three phone numbers, the user document directly embeds a list containing those three numbers.
To see the mechanical difference, imagine storing a user who placed an order. In a relational approach, we execute two distinct lookups or combine two tables using an inner join on the user identifier. In a document approach, we fetch a single document that already contains the nested order records.
The relational model prioritizes data consistency and deduplication at the cost of requiring cross-table joins. The document model prioritizes retrieval speed for known access patterns by co-locating related data within one object at the cost of duplicate data across documents.
Simulating relational table lookup with join versus document store lookup
# Relational representation: separate tables linked by keysusers_table = { 1: {"name": "Alice", "email": "alice@example.com"}}orders_table = [ {"order_id": 101, "user_id": 1, "total": 49.99}, {"order_id": 102, "user_id": 1, "total": 15.50}]def get_user_orders_relational(user_id): user = users_table.get(user_id) if not user: return None # Manual join operation orders = [o for o in orders_table if o["user_id"] == user_id] return {"user": user, "orders": orders}# Non-relational (Document) representation: embedded nested structuredocuments_collection = { 1: { "name": "Alice", "email": "alice@example.com", "orders": [ {"order_id": 101, "total": 49.99}, {"order_id": 102, "total": 15.50} ] }}def get_user_orders_document(user_id): # Direct primary key retrieval; no join required return documents_collection.get(user_id)print("Relational join result:", get_user_orders_relational(1))print("Document read result:", get_user_orders_document(1))
Key takeaways
- Relational databases isolate entities into normalized tables connected via foreign keys.
- Non-relational document databases embed related attributes directly inside a self-contained record.
- Joins assemble normalized data at read time, whereas document stores pre-aggregate data at write time.
Level 2 · Intermediate: ACID guarantees, indexing strategies, and horizontal sharding
Relational databases are built around ACID guarantees: Atomicity, Consistency, Isolation, and Durability. Atomicity ensures that a sequence of operations either entirely succeeds or entirely rolls back. Consistency guarantees that every transaction moves the database from one valid state to another according to all schema rules and constraints. Isolation ensures that concurrent transactions do not interfere with one another. Durability guarantees that committed transactions survive hardware failures through a Write-Ahead Log (WAL).
Most non-relational databases weaken these guarantees across multiple records to achieve horizontal scalability. Under the CAP theorem, a distributed data store can guarantee at most two out of Consistency, Availability, and Partition Tolerance. When network partitions occur, distributed NoSQL systems often choose Availability, adopting Eventual Consistency. In an eventually consistent system, writes are acknowledged before propagating to all replicas; readers may briefly observe stale data until all nodes synchronize.
Indexes behave differently across the two models. Relational systems primarily use B-Trees or B+ Trees, which provide logarithmic time complexity for point reads and range scans while keeping tabular data ordered. Non-relational systems often use Log-Structured Merge-trees (LSM-trees) for write-heavy workloads, or distributed hash partitions where records are routed using a hash function applied to a partition key.
Horizontal scaling, or sharding, involves splitting a dataset across multiple machines. In a relational database, sharding breaks joins and foreign key constraints across physical boundaries, requiring complex distributed transaction coordinators such as two-phase commit protocols. Non-relational systems are built from the ground up for sharding: every read and write specifies a partition key, allowing the database router to target the exact node holding that partition directly.
Consistent hashing simulator for horizontal partition routing
import hashlibimport bisectclass DistributedPartitionRouter: def __init__(self, nodes=None, virtual_nodes=3): self.virtual_nodes = virtual_nodes self.ring = [] self.node_map = {} for node in (nodes or []): self.add_node(node) def _hash(self, key): return int(hashlib.md5(key.encode('utf-8')).hexdigest(), 16) def add_node(self, node): for i in range(self.virtual_nodes): v_key = f"{node}#vn{i}" h = self._hash(v_key) bisect.insort(self.ring, h) self.node_map[h] = node def get_node(self, key): if not self.ring: return None h = self._hash(key) idx = bisect.bisect_right(self.ring, h) if idx == len(self.ring): idx = 0 return self.node_map[self.ring[idx]]router = DistributedPartitionRouter(["node-alpha", "node-beta", "node-gamma"])print("User 1001 maps to:", router.get_node("user_1001"))print("User 1002 maps to:", router.get_node("user_1002"))print("User 1003 maps to:", router.get_node("user_1003"))
Key takeaways
- ACID transactions ensure strong consistency across multi-table operations at the expense of distributed latency.
- Non-relational architectures favor horizontal scalability by partitioning data along explicit partition keys.
- Consistent hashing enables dynamic cluster expansion without remapping the entire keyspace.
Level 3 · Advanced: Storage engines, cross-partition operations, and hybrid architectures
The underlying storage engine dictates performance limits. Relational engines like InnoDB (MySQL) use B+ Trees where all data resides in leaf nodes and internal nodes store routing keys. This structure provides predictable O(log N) random access and efficient range queries, but random writes incur in-place page updates that trigger random disk I/O. Non-relational databases like Cassandra and RocksDB use Log-Structured Merge-trees (LSM-trees). An LSM-tree buffers incoming writes in memory (MemTable) and sequentially appends them to a commit log. When full, it flushes immutable Sorted String Tables (SSTables) to disk, converting random writes into sequential writes at the cost of read amplification managed by Bloom filters.
When business requirements demand querying across attributes that do not include the partition key, non-relational systems encounter severe architectural bottlenecks. A scatter-gather query must broadcast the read request to every single node in the cluster, wait for responses, and merge them at the coordinator. If one node experiences a latency spike, the entire query stalls. Relational systems avoid scatter-gather when hosted on a single large node, executing complex nested queries with index intersections and cost-based query optimizers.
Modern system design frequently converges on polyglot persistence or hybrid architectures (NewSQL). Polyglot persistence delegates transactional writes, invoicing, and inventory tracking to an ACID-compliant relational database (like PostgreSQL), while high-throughput, unstructured streams, session data, or telemetry stream into document or wide-column stores (like MongoDB or Cassandra). Meanwhile, NewSQL engines (such as CockroachDB or Google Spanner) leverage distributed consensus protocols like Raft or Paxos, paired with atomic clocks, to provide horizontal scaling without abandoning relational schemas or ACID guarantees.
Selecting between these systems requires analyzing access patterns. If queries require arbitrary aggregations, frequent structural modifications to relationships, and multi-record atomic guarantees, relational databases remain optimal. If throughput targets exceed single-node write capabilities, write workloads follow predefined key lookups, and schemas fluctuate continuously, non-relational distributed databases are appropriate.
In-memory LSM-tree write buffer with memtable and immutable SSTable flush
import timeclass SimpleLSMNode: def __init__(self, threshold=3): self.threshold = threshold self.memtable = {} self.sstables = [] def put(self, key, value): self.memtable[key] = (value, time.time()) if len(self.memtable) >= self.threshold: self._flush() def _flush(self): sorted_items = sorted(self.memtable.items(), key=lambda x: x[0]) self.sstables.append(sorted_items) self.memtable = {} def get(self, key): if key in self.memtable: return self.memtable[key][0] for sstable in reversed(self.sstables): # Binary search over sorted immutable table keys = [k for k, _ in sstable] low, high = 0, len(keys) - 1 while low <= high: mid = (low + high) // 2 if keys[mid] == key: return sstable[mid][1][0] elif keys[mid] < key: low = mid + 1 else: high = mid - 1 return Nonelsm = SimpleLSMNode(threshold=2)lsm.put("alpha", 1)lsm.put("beta", 2) # Triggers flush to SSTable 1lsm.put("gamma", 3)print("Read alpha:", lsm.get("alpha"))print("Read gamma:", lsm.get("gamma"))
Key takeaways
- B+ Trees optimize for point reads and range scans; LSM-trees optimize for continuous high-throughput write streams.
- Scatter-gather queries in partitioned systems incur latency tails equal to the slowest node in the cluster.
- Polyglot persistence pairs relational engines for core transactional integrity with non-relational engines for scale-out workloads.
Complexity
- Time: Point lookup by primary key is O(log N) in B+ Tree relational stores, and average O(1) in hashed non-relational stores or O(log N) across SSTables in LSM stores.
- Space: O(N) total disk footprint, where non-relational stores typically consume O(N * D) space due to data denormalization and duplication factor D.
Relational databases minimize disk usage through normalization (storing each fact once) but require logarithmic tree traversals and join computation. Non-relational systems trade disk space by duplicating data inside documents to enable single-read lookups, or append-only write streams that defer cleanup to background compaction.
Common mistakes
- Treating a document database like a relational database by storing foreign identifiers and executing application-side joins across multiple collections.
- Prematurely choosing a distributed NoSQL database for small datasets that would fit into memory on a single relational instance, adding cluster management complexity with no throughput benefit.
- Using a non-relational database without defining clear partition keys, leading to unbalanced hot-spotting on a single node.
- Assuming eventual consistency behaves like strong consistency, causing race conditions in financial or inventory mutations.
- Over-normalizing a high-throughput relational database to the point where simple operations require six-way table joins on critical paths.
Practice problems
- E-Commerce Schema Modeling (easy). Hint: Design two schemas for a product catalog with arbitrary attributes like size and color: one in PostgreSQL using JSONB or EAV, and one in MongoDB.
- Distributed Partition Router with Replication (medium). Hint: Extend a consistent hashing ring so that each written key is mirrored across the next N distinct physical nodes on the ring to prevent data loss on node failure.
- Transactional Outbox Pattern Implementation (hard). Hint: Ensure an ACID database update and a non-relational event stream publish occur atomically without two-phase commit by committing outbox records within the primary relational transaction.
Summary
Relational databases use structured tables, strict schemas, and B+ Trees to ensure strong consistency and flexible relational queries via joins. Non-relational databases prioritize write throughput, flexible schemas, and horizontal scalability by utilizing key-value, document, or wide-column models with append-friendly structures like LSM-trees. Modern architecture evaluates data access patterns and scaling limits to employ each system where its architectural trade-offs provide the highest efficiency.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 15 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!