08 SQL Vs NoSQL
08 SQL Vs NoSQL
S Q L V S N O S Q L — PA R T 1
1 What Is a Database?
DEFINITION
Every app you use — Instagram, WhatsApp, your banking app — relies on a database to store
its data.
2 What Is a DBMS?
DEFINITION
A Database Management System (DBMS) is the software layer that manages the database. It
is the middle-man between your application code and the raw data. It handles security,
querying, indexing, backups, and ensures data integrity.
Example: MySQL (the DBMS) manages a MySQL database. The two main families of DBMS are
Relational (SQL) and Non-Relational (NoSQL).
[Link] 1/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
LIBRARY ANALOGY
DBMS
YOUR APPLICATION queries reads/writes DATABASE
(MySQL, PostgreSQL, MongoDB)
([Link], Python, Java) (Actual data on disk)
Security · Querying · Indexing
Sends SQL or API queries Backups · Integrity · Concurrency Tables, Documents, Files
THE QUESTION
"Would you use SQL or NoSQL here?" — This is one of the most common system design
interview questions. Choosing wrong means you'll either struggle to scale past a few million
users (wrong NoSQL choice) or spend months debugging data inconsistencies that corrupt
your business logic (wrong SQL choice).
SQL or NoSQL?
[Link] 2/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
What SQL is, how relational databases work internally, ACID, JOINs, normalisation, and when
to choose SQL
1 What Is SQL?
DEFINITION
SQL stands for Structured Query Language. It is both the language used to interact with
relational databases and the informal name for relational databases themselves.
SQL databases organise data into tables (like spreadsheets) with rows and columns. Each
table represents one type of entity (Users, Orders, Products), and relationships between tables
are defined using primary and foreign keys.
EXCEL ANALOGY
A SQL database is like a well-organised Excel workbook with multiple sheets. Each sheet has
predefined column headers. Every row must follow the same structure. You can cross-
reference data between sheets using a shared ID column.
id (PK) name email city FOREIGN KEY id (PK) user_id (FK) total status
orders.user_id → [Link]
1 Amit amit@.. Mumbai 101 1 5000 done
2 Priya priya@.. Delhi 102 3 2500 pending
3 Sara sara@.. BLR 103 1 8000 done
[Link] 3/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
WHAT IS NORMALISATION?
The process of organising tables to eliminate data redundancy and ensure data integrity. You
break one big table into multiple smaller, related tables so that each piece of data is stored
exactly once.
[Link] 4/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
┌────┬───────┬─────────┐ ┌─────┬─────────┬───────┬───────────┐
│ id │ name │ email │ │ id │ user_id │ total │ product │
├────┼───────┼─────────┤ ├─────┼─────────┼───────┼───────────┤
│ 1 │ Amit │ amit@.. │ │ 101 │ 1 │ 5000 │ Laptop │
│ 2 │ Priya │ priya@..│ │ 102 │ 2 │ 2500 │ Headphone │
└────┴───────┴─────────┘ │ 103 │ 1 │ 8000 │ Phone │
└─────┴─────────┴───────┴───────────┘
Amit's data stored ONCE. Orders reference via FK (user_id=1).
Change email? Update ONE row. Always consistent.
LEFT JOIN: ALL rows from left table + matching rows from right.
ALL users + their orders (if any). Users without orders show NULL.
RIGHT JOIN: ALL rows from right table + matching rows from left.
ALL orders + their user info. Orphan orders show NULL user.
FULL JOIN: ALL rows from BOTH tables. Non-matching show NULL.
Every user and every order, matched where possible.
A B
[Link] 5/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
WHAT IS ACID?
ACID is a set of four properties that guarantee database transactions are processed reliably.
This is the cornerstone of SQL databases and the reason banks, payment systems, and
anything involving money use SQL.
A = ATOMICITY
"All or nothing." A transaction either completes fully or not at all.
If transferring ₹5000 from Account A to B:
Step 1: Debit A by 5000
Step 2: Credit B by 5000
If Step 2 fails, Step 1 is ROLLED BACK. Money doesn't vanish.
C = CONSISTENCY
"Always valid state." The database moves from one valid state to another.
Constraints (foreign keys, unique, NOT NULL) are always enforced.
You can never have an order pointing to a user_id that doesn't exist.
I = ISOLATION
"Transactions don't interfere." Multiple transactions running at
the same time don't see each other's partial changes.
User A transferring money and User B checking balance simultaneously
— B sees either the state BEFORE or AFTER, never a half-done state.
D = DURABILITY
"Once committed, it's permanent." After a transaction commits,
the data survives even if the server crashes or loses power.
The database writes to disk (write-ahead log) before confirming.
A C I D
Atomicity Consistency Isolation Durability
All or nothing. Always valid state. No interference. Once committed,
Debit+Credit both Constraints always Concurrent txns don't it's permanent. Survives
happen, or neither. enforced. No bad data. see partial changes. crashes & power loss.
[Link] 6/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
You transfer ₹5000 from your account to a friend. Atomicity ensures the money is both
debited from you AND credited to your friend — or neither happens. Consistency ensures total
money in the system doesn't change. Isolation ensures if someone checks your balance mid-
transfer, they see the old or new balance, not a weird in-between. Durability ensures once the
transfer is confirmed, it stays even if the bank's server crashes.
SQL is divided into four sub-languages, each for a different type of operation:
DDL Data Definition CREATE , ALTER , DROP Define and modify database
Language structure (tables, columns)
DML Data Manipulation SELECT , INSERT , Read and write actual data
Language UPDATE , DELETE
DCL — Permissions:
[Link] 7/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
TCL — Transactions:
BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE id = 2;
COMMIT; -- both succeed together (atomicity!)
-- or ROLLBACK; if something goes wrong
SQL databases traditionally scale vertically — you make the single server bigger (more RAM,
faster CPU, bigger disk). This works until you hit hardware limits. Horizontal scaling (adding
more servers) is possible but complex for SQL because JOINs across servers are hard and
maintaining ACID across distributed nodes is expensive.
[Link] 8/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
BIGGER Server
More RAM, CPU, Disk
Srv 5 Srv 6 →keep adding!
[Link] 9/11
04/04/2026, 12:57 SQL vs NoSQL — Part 1: The Big Picture & SQL Deep Dive
1. Your data has clear relationships (users have orders, orders have items)
2. You need ACID transactions (money transfers, inventory, bookings)
3. Your schema is well-defined and stable (not changing every week)
4. You need complex queries — JOINs, aggregations, GROUP BY, subqueries
5. Data integrity is more important than raw write speed
6. You need reporting and analytics on structured data
WHAT IS SQL?
Structured Query Language. Data in tables (rows + columns). Relationships via primary/foreign
keys. Schema enforced — every row must match the structure.
CORE CONCEPTS
Table = rows + columns. PK = unique row ID. FK = link to another table's PK. Index = fast lookup
(B+ Tree). Normalisation = eliminate redundancy.
ACID GUARANTEES
Atomicity (all or nothing) · Consistency (always valid) · Isolation (no interference) · Durability
(permanent after commit)
SQL SUB-LANGUAGES
DDL = CREATE/ALTER/DROP (structure). DML = SELECT/INSERT/UPDATE/DELETE (data). DCL =
GRANT/REVOKE (permissions). TCL = COMMIT/ROLLBACK (transactions).
SCALING
Vertical (scale up) = bigger server. Simple but hits ceiling.
Horizontal (scale out) = more servers. Possible but complex for SQL (JOINs across nodes,
distributed ACID).
POPULAR DATABASES
PostgreSQL (complex queries, JSON). MySQL (web apps, LAMP). SQL Server (enterprise/BI).
Oracle (mission-critical). SQLite (embedded/mobile).
[Link] 11/11
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
S Q L V S N O S Q L — PA R T 2
1 What Is NoSQL?
DEFINITION
NoSQL stands for "Not Only SQL". It is a broad family of databases that don't use the
relational table model. Instead of one single design (tables + SQL), NoSQL offers multiple
data models, each optimised for a specific type of data or workload.
The common thread: they sacrifice some consistency guarantees in exchange for horizontal
scalability, schema flexibility, and high availability.
If SQL is one type of organised filing cabinet (rigid but reliable), NoSQL is a collection of very
different storage tools — a backpack, a whiteboard, a spreadsheet, a corkboard — each
perfect for a specific purpose. You pick the tool that fits your data, not force your data into one
shape.
INTERVIEW CRITICAL
[Link] 1/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
You must know all 6 types, what they store, and when to use them. Each type is designed for a
fundamentally different kind of data. Interviewers will ask: "What type of NoSQL would you use
for X?" — and you need to pick the right one with reasoning.
① KEY-VALUE ④ GRAPH
Giant hash map. GET/SET. Nodes + edges. Relationships.
Redis, DynamoDB Neo4j, Neptune
NoSQL
② DOCUMENT 6 Types
⑤ IN-MEMORY
JSON docs, flexible schema. RAM-first. Microsecond latency.
MongoDB, Firestore Redis, Memcached
③ WIDE-COLUMN ⑥ TIME-SERIES
Flexible cols per row. Massive writes. Timestamped data. Metrics.
Cassandra, HBase InfluxDB, Prometheus
TYPE 1
WHAT IS IT?
Stores data as simple key → value pairs. The key is a unique identifier. The value can
be anything: a string, number, JSON blob, or binary data. The database doesn't care
what's inside the value — it just stores and retrieves it by key. Operations are extremely
fast: GET , SET , DELETE .
KEY VALUE
─────────────────────────────────────────────────
"user:1001:session" → "abc123xyz789"
"user:1001:cart" → {"items": [{"id": 42, "qty": 2}]}
"rate_limit:ip:1.2.3" → "47"
"cache:product:555" → "{name: 'Laptop', price: 75000}"
"leaderboard:game1" → [{"user": "amit", "score": 9500}, ...]
Operations:
[Link] 2/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
Use Cases: Session storage, user preferences, shopping carts, rate limiting, real-time
leaderboards, caching results of expensive queries.
Examples: Redis (most popular), Amazon DynamoDB, Azure Cosmos DB, Memcached.
It's essentially a giant hash table. hash(key) → memory location → value. O(1) lookups.
Redis stores everything in RAM — reads take microseconds, not milliseconds. This is
why it's used as a caching layer in front of slower databases.
TYPE 2
WHAT IS IT?
{
"_id": "user_1001",
"name": "Amit Sharma",
"email": "amit@[Link]",
"age": 28,
"address": { ← nested object
"city": "Mumbai",
"state": "Maharashtra",
"pin": "400001"
[Link] 3/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
},
"orders": [ ← nested array
{"id": "ord_501", "total": 5000, "status": "delivered"},
{"id": "ord_502", "total": 2500, "status": "pending"}
],
"preferences": { ← flexible fields
"theme": "dark",
"notifications": true
},
"tags": ["premium", "early_adopter"] ← arrays
}
Use Cases: User profiles, product catalogs, blog posts with comments, content
management systems, e-commerce catalogs, configuration storage.
Examples: MongoDB (most popular), CouchDB, Amazon DocumentDB, Firestore
(Firebase).
SQL: User data split across users, addresses, orders tables → needs JOINs → data
always consistent → but slower for "get everything about this user."
Document: Everything for a user in ONE document → no JOINs → blazing fast reads →
but if you update the address format, you must update each document individually.
TYPE 3
WHAT IS IT?
Similar to SQL tables but each row can have completely different columns. Data is
stored in column families rather than rows. Optimised for writing massive amounts of
data and for time-series queries ("give me all records between time A and time B").
Built for distribution across many nodes.
[Link] 4/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
Use Cases: Time-series data, IoT sensor logs, activity feeds, messaging platforms,
telemetry, analytics, write-heavy workloads with billions of events.
Examples: Apache Cassandra (most popular), HBase, Google Bigtable (the original),
Azure Table Storage.
TYPE 4
WHAT IS IT?
Data is stored as nodes (entities) and edges (relationships between entities). Ideal
when the relationships between data are just as important as the data itself.
[Link] 5/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
SQL handles relationships via JOINs. For "friends of friends," you need a self-JOIN. For
"friends of friends of friends," you need another JOIN. Each level of depth adds
another JOIN — and SQL JOINs get exponentially slower. Graph databases store
relationships as first-class citizens — traversing 5 levels deep is just as fast as
traversing 1 level. That's the fundamental difference.
[Link] 6/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
TYPE 5
WHAT IS IT?
Data is stored primarily in RAM (memory) rather than on disk. This eliminates disk I/O,
making reads and writes orders of magnitude faster. Trade-off: data is volatile (lost on
power failure) unless persistence mechanisms are enabled. Used as a speed layer in
front of other databases.
Without cache:
App → Database (disk) → 5-50ms per read
TYPICAL PATTERN:
1. App checks Redis first (cache hit? → return instantly)
2. Cache miss → query actual database
3. Store result in Redis with TTL (e.g., expire in 5 minutes)
4. Next request for same data → served from RAM
PERSISTENCE IN REDIS
[Link] 7/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
slower.
Most production Redis setups use both for safety.
TYPE 6
WHAT IS IT?
Specialised database for storing data points indexed by time. Data is naturally ordered
chronologically. Highly optimised for ingesting millions of events per second, and for
queries like "average CPU over the last 5 minutes" or "all readings between 9am and
10am."
METRIC: server_cpu_usage
┌─────────────────────┬───────────┬──────────┐
│ timestamp │ server_id │ cpu_% │
├─────────────────────┼───────────┼──────────┤
│ 2024-03-15 09:00:01 │ srv-01 │ 45.2 │
│ 2024-03-15 09:00:01 │ srv-02 │ 72.8 │
│ 2024-03-15 09:00:02 │ srv-01 │ 47.1 │
│ 2024-03-15 09:00:02 │ srv-02 │ 71.5 │
│ 2024-03-15 09:00:03 │ srv-01 │ 52.3 │
│ ...millions more... │ │ │
└─────────────────────┴───────────┴──────────┘
SPECIAL FEATURES:
• Automatic downsampling: keep per-second data for 1 day,
per-minute data for 1 month, per-hour data for 1 year
• Built-in aggregation: AVG, MIN, MAX, PERCENTILE over time windows
• Compression: timestamps compress extremely well (sequential)
• Retention policies: auto-delete data older than X days
Use Cases: DevOps monitoring (CPU, memory metrics), IoT sensor data, financial tick
data, application performance monitoring (APM), smart grid data, weather data.
[Link] 8/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
TOP
TYPE DATA MODEL BEST FOR
EXAMPLE
Key-Value key → value (any blob) Caching, sessions, rate limiting Redis
→ Built for massive write throughput → No native JOINs — complex queries are
hard
→ High availability and fault tolerance
→ Limited multi-document transaction
→ Each type optimised for its use case
support
→ Multi-region distribution is built-in
→ No enforced schema = risky data quality
[Link] 9/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
ACID is a set of four properties that guarantee database transactions are processed reliably
and that data is never left in a corrupted state, even during system failures. Every major SQL
database is ACID-compliant by default.
[Link] 10/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
WHAT IS BASE?
BASE is the alternative philosophy adopted by most distributed NoSQL databases. It relaxes
ACID's strict consistency guarantees to achieve higher availability and easier horizontal
scaling.
BA = BASICALLY AVAILABLE
The system guarantees SOME response to every request,
even during partial failures. The response might be stale
or from a replica, but the system never goes completely down.
S = SOFT STATE
The system's state may change over time even WITHOUT new inputs,
as data propagates between nodes asynchronously.
Example: A social media post you just liked shows 100 likes to you,
but still shows 99 to someone in another region — the update
hasn't propagated to their node yet.
E = EVENTUALLY CONSISTENT
Given enough time with no new updates, ALL nodes will converge
to the same data. Consistency is guaranteed EVENTUALLY — not
immediately.
[Link] 11/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
T = 2s
Node A Node B Node C
Propagating B is catching up, C still behind
✓ Updated ⟳ Syncing ✗ Stale
T = 5s
Node A Node B Node C
Converged! ALL nodes now have same data ✓
✓ Updated ✓ Updated ✓ Updated
Failure Handling Roll back entire transaction Resolve conflicts after the fact
[Link] 12/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
Amazon's shopping cart uses BASE/eventual consistency intentionally. They would rather
show a slightly stale cart than fail to load the page.
But Amazon's payment processing uses ACID/strong consistency — you can NEVER have
eventual consistency for money. The payment must either go through completely or not at all.
Real systems use BOTH. The same company picks ACID for critical paths and BASE for
everything else. This is the nuanced answer interviewers want.
In a distributed system, you can only guarantee two out of three properties at the same time:
Since network partitions always happen in distributed systems, you really choose between
CP (consistency + partition tolerance) or AP (availability + partition tolerance).
AP Systems CP Systems
Cassandra, DynamoDB, CouchDB MongoDB, HBase, Redis
Available but may serve stale data Consistent but may reject reads
A P
Availability Partition Tol.
CA (Consistency + Availability):
→ Only possible on SINGLE node (no partitions)
→ Traditional single-server SQL databases (PostgreSQL, MySQL)
→ Not truly distributed — if that node fails, everything fails
6 NOSQL TYPES
1. Key-Value: hash map. GET/SET. Redis, DynamoDB. → sessions, cache, rate limiting
2. Document: JSON docs. MongoDB, Firestore. → user profiles, catalogs, CMS
3. Wide-Column: flexible cols/row. Cassandra, HBase. → IoT, time-series, massive writes
4. Graph: nodes + edges. Neo4j, Neptune. → social networks, fraud, recommendations
5. In-Memory: RAM-first. Redis, Memcached. → caching layer, real-time, leaderboards
6. Time-Series: timestamped. InfluxDB, Prometheus. → monitoring, IoT metrics, APM
ACID (SQL)
Atomicity (all or nothing) · Consistency (always valid) · Isolation (no interference) · Durability
(permanent). Used for: money, inventory, medical.
BASE (NOSQL)
Basically Available (always responds) · Soft state (may change without input) · Eventually
consistent (converges over time). Used for: social, analytics, IoT.
[Link] 14/15
04/04/2026, 12:57 SQL vs NoSQL — Part 2: NoSQL Deep Dive & ACID vs BASE
CAP THEOREM
Pick 2 of 3: Consistency, Availability, Partition tolerance. P is mandatory in distributed systems.
Choose CP (MongoDB, HBase) or AP (Cassandra, DynamoDB).
[Link] 15/15
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
S Q L V S N O S Q L — PA R T 3
Data Model Tables, rows, Documents, KV, Graph, Structured → SQL; Flexible →
columns Column NoSQL
Scalability Vertical (scale up) Horizontal (scale out) <10TB → SQL; >100TB →
NoSQL
Query Power Rich JOINs, Simple key lookups Ad-hoc analytics → SQL
aggregations
[Link] 1/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
Write Speed Moderate (ACID High (no coordination) High write volume → NoSQL
overhead)
Read Speed Fast with indexes + Fast for key-based Complex reads → SQL;
JOINs reads Simple → NoSQL
Schema Migration needed Just start writing new Rapid iteration → NoSQL
Change fields
→ You need ACID transactions across → You need to scale beyond 100TB or 1M+
multiple records writes/second
→ Your data has complex relationships → Can tolerate eventual consistency for your
requiring JOINs domain
→ Dataset fits under ~10TB and write load < → Schema evolves rapidly or varies per
100K writes/sec record
→ You need ad-hoc analytics and complex → Primary queries are simple key-based
reporting lookups
→ Domain is well-defined and schema is → High availability across regions is critical
stable → Data is naturally document-shaped or
→ Team has strong SQL expertise graph-shaped
→ Compliance or audit requirements mandate → Append-only data: logs, events, sensor
strong consistency readings
[Link] 2/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
NO
NO
The answer is ALWAYS: "It depends on the consistency requirements, expected scale, team
expertise, and nature of the data." Show nuance. Most large systems use BOTH — SQL for
transactional paths, NoSQL for scale, caching, and analytics.
1 Normalisation vs Denormalisation
Two opposite database design strategies. Understanding when to use each is a classic
interview question.
WHAT IS IT?
[Link] 3/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
Normalisation organises tables to reduce data duplication. The same piece of information is
stored only once, and other tables reference it. There are formal levels called Normal Forms.
NORMAL
RULE EXAMPLE
FORM
1NF Atomic values only. No repeating groups or Split "phone1, phone2" into separate
arrays. rows
3NF Meets 2NF + no transitive dependency (non- City shouldn't depend on zip_code in
key → non-key) Orders table
WHAT IS IT?
[Link] 4/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
To show "Amit bought Laptop for 5000" → read ONE document. No JOIN!
Change Amit's name? Must update EVERY document that has his name.
NORMALISED DENORMALISED
Users Orders Products One Big Document / Table
WHAT IS SHARDING?
Sharding splits a large table across multiple database servers. Each server holds a subset
(shard) of the data. This is how SQL databases can scale horizontally despite not being built
for it natively.
┌──────────────────┐ ┌──────────────────┐
│ Shard 1: Users │ │ Shard 2: Users │
│ A-F (25M users) │ │ G-M (25M users) │
└──────────────────┘ └──────────────────┘
┌──────────────────┐ ┌──────────────────┐
│ Shard 3: Users │ │ Shard 4: Users │
│ N-S (25M users) │ │ T-Z (25M users) │
└──────────────────┘ └──────────────────┘
Range- Shard by value ranges. Users Simple. Range Hot shards if distribution is
Based A-M → Server 1; N-Z → queries stay on one uneven (more users start
Server 2 shard. with "S" than "X")
Directory- A lookup table maps each Most flexible. Can Lookup table itself can be
Based key → specific shard move individual bottleneck + single point of
keys. failure.
Cross-shard JOINs are very slow or impossible — you can't easily JOIN data that lives on
different servers.
ACID transactions across shards require expensive two-phase commit (2PC) protocol — all
shards must agree before committing.
[Link] 6/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
This is why sharding is a last resort for SQL databases — try vertical scaling, read replicas,
and caching first.
3 Database Federation
WHAT IS FEDERATION?
┌─────────────────────┐
│ FEDERATION LAYER │ ← routes queries to correct DB
│ (unified endpoint) │
└──────┬──────┬───────┘
│ │ │
┌────────────┤ │ ├────────────┐
↓ ↓ ↓ ↓ ↓
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Users DB │ │ Orders DB │ │Products DB │
│ (PostgreSQL) │ │ (MySQL) │ │ (MongoDB) │
└──────────────┘ └──────────────┘ └──────────────┘
BENEFITS:
• Transparency: App queries one endpoint, federation routes to correct DB
• Heterogeneity: Each DB can be a different type!
• Autonomy: Each database is self-contained, updated independently
• Natural fit for MICROSERVICES (each service has its own DB)
TRADE-OFFS:
• Cross-database JOINs are slow
• Global transactions across federated DBs are complex
• Added complexity in the federation layer
[Link] 7/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
1 Data Replication
WHAT IS REPLICATION?
Copying data from one location (the primary/source) to one or more other locations
(replicas/secondaries). Replication can be synchronous or asynchronous, and creates
multiple copies across different servers or geographic locations.
Replication is like sending a mass email. You write one email and it gets delivered to 10 people.
Each recipient gets their own copy. The delivery can be instant (sync) or delayed by a few
seconds (async). You control who gets updates and when.
Synchronous Primary waits for ALL Zero data loss Google Spanner, PG
replicas to confirm before synchronous standby
ACK to client
Asynchronous Primary confirms Fast but risk of data MySQL read replicas,
immediately, replicates in loss if primary crashes MongoDB replica sets
background
[Link] 8/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
Waits for ALL to ACK Confirms IMMEDIATELY Waits for at least ONE
✓ Zero data loss ✓ Fast writes ✓ Reduced risk
1. READ SCALING
Add read replicas to distribute read traffic.
Primary handles ALL writes; replicas handle reads.
2. GEOGRAPHIC DISTRIBUTION
Replicate to data centres in Asia, Europe, US
for low-latency local reads.
3. DISASTER RECOVERY
If primary data centre fails, promote a replica to primary.
5. ZERO-DOWNTIME MIGRATIONS
Replicate to new server, then switch over without downtime.
2 Data Mirroring
WHAT IS MIRRORING?
[Link] 9/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
current duplicate — not a slightly-behind copy. Used specifically for high availability and
instant failover.
SHADOW ANALOGY
Mirroring is like a live shadow. When a dancer moves, the shadow moves at exactly the same
instant. There is never a gap between the two. If the dancer "fails," the shadow can
immediately take over without any missed frames.
ARCHITECTURE:
┌──────────────┐ ┌──────────────┐
│ PRINCIPAL │ ──────→ │ MIRROR │
│ (Primary) │ sync │ (Standby) │
│ Server │ write │ Server │
└──────────────┘ └──────────────┘
↑ ↑
│ ┌──────────────┘
│ │
┌─────────────────┐
│ WITNESS │ ← optional: automates failover decisions
│ (monitors both) │ if principal fails, witness + mirror
└─────────────────┘ vote to promote mirror to principal
FLOW:
1. Client sends write to Principal
2. Principal writes AND sends to Mirror simultaneously
3. Mirror applies transaction, sends ACK
4. ONLY after both have the data → client gets confirmation
5. If Principal fails → Witness detects → Mirror promoted → zero downtime
[Link] 10/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
Primary Purpose Availability, load balancing, analytics High availability, instant failover
Performance Async: minimal; Sync: write latency Higher write latency (wait for mirror
Impact ACK)
Flexibility Very flexible — many configurations More rigid — exact replication only
Use Cases Read scaling, reporting, geo- HA systems, financial, critical data
distribution
Consistency Async replicas may serve stale Mirror always has same data
reads
Cost Lower per replica (async = cheap) Higher (synchronous = double write
cost)
INTERVIEW SUMMARY
Replication = copies for scale + backup (can be async). Flexible, many copies, may have lag.
Mirroring = always-on exact copy for zero-downtime failover (always sync). Rigid, 1-to-1, zero
lag.
Most enterprise systems use BOTH: mirroring for HA failover + async replication for read
scaling.
[Link] 11/12
04/04/2026, 12:57 SQL vs NoSQL — Part 3: Comparison, Sharding, Replication & Advanced Topics
NORMALISATION VS DENORMALISATION
Normalised: no duplication, FK references, JOINs needed, consistent. Best for OLTP (banking).
Denormalised: data duplicated, no JOINs, fast reads, risk of inconsistency. Best for OLAP /
reads.
FEDERATION
Split by function: Users DB, Orders DB, Products DB on separate servers. Federation layer
routes queries. Natural fit for microservices. Cross-DB JOINs are complex.
REPLICATION
Sync: wait for all replicas → zero data loss, slower. Async: confirm immediately → fast, risk of
loss. Semi-sync: wait for ONE → middle ground.
Use cases: read scaling, geo-distribution, disaster recovery, analytics offloading.
MIRRORING
Always synchronous, 1-to-1, zero lag. Principal + Mirror + Witness. Instant automatic failover.
Used for HA, financial, healthcare.
REPLICATION VS MIRRORING
Replication = flexible, many copies, can be async. For scale + backup.
Mirroring = rigid, exact copy, always sync. For zero-downtime failover.
Enterprise systems use both: mirroring for HA + async replication for read scaling.
[Link] 12/12
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
S Q L V S N O S Q L — PA R T 4
Interviewers don't just want to know SQL vs NoSQL theory — they want to see that you
understand how these decisions play out in real systems at real scale. Referencing actual
company decisions shows depth and credibility. These four case studies cover the four most
common architectural patterns.
CASE STUDY 1
The Problem
Instagram launched with PostgreSQL and scaled to 300 million daily active users. Two very
different data needs emerged:
→ User profiles and account data → Activity feeds (your home feed)
→ Follower/following relationships → Likes (millions per second globally)
→ Photo metadata (which photo belongs to → Notifications
whom) → Eventual consistency is fine here
→ You can NEVER show a photo in the wrong → Seeing 99 likes vs 100 for 2 seconds? No
account problem
→ Follower counts must be accurate → Needs millions of writes/second
[Link] 1/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
INTERVIEW TAKEAWAY
Instagram is the gold-standard polyglot persistence example. The lesson: don't force one
database to do everything. Use SQL where consistency matters and NoSQL where scale
matters. When interviewers ask "Would you use SQL or NoSQL?", the best answer is often: "I'd
use BOTH — here's how I'd split the data."
CASE STUDY 2
The Problem
Discord initially chose MongoDB for message storage — attracted by its flexible JSON schema
and easy development setup. But as they scaled past 100 million messages per channel,
serious problems emerged:
→ Read latency degraded badly at scale → Append-only (never updated after posting)
→ MongoDB's storage engine wasn't → Always queried by time range ("messages
optimised for time-series data in channel X between Y and Z")
→ Messages are always queried by TIME → Predictable low latency at massive scale
range, not by flexible fields → Simple key-based access pattern
→ Sharding became operationally nightmarish → Write-optimised for high throughput
→ Hot partitions on popular channels
[Link] 3/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
QUERY PATTERN:
SELECT * FROM messages
WHERE channel_id = 'abc123'
AND bucket = '2024-03-15'
AND message_id > [timestamp_for_9am]
AND message_id < [timestamp_for_10am];
→ Reads EXACTLY the messages needed, nothing more.
NoSQL is not one thing. MongoDB's document flexibility was NOT the right NoSQL type for
time-series messages. Cassandra's write-optimised wide-column model was. The lesson:
don't just choose "NoSQL" — choose the right TYPE of NoSQL for your specific access
pattern.
[Link] 4/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
CASE STUDY 3
The Problem
Twitter started with Ruby on Rails and MySQL for all data, including tweets. As Twitter grew
from thousands to hundreds of millions of users, MySQL couldn't handle the volume:
TWEET CHARACTERISTICS:
• 300K+ tweets posted per hour
• Tweets are IMMUTABLE (never edited after posting — at that time)
• Accessed primarily by tweet_id or user_id
• Need enormous write throughput + read throughput
• Timeline generation requires reading tweets from 100s of followed users
[Link] 5/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
Twitter Application
Apache Kafka:
→ Event streaming between services
→ When a tweet is posted, Kafka distributes the event to:
- Timeline service (add to followers' feeds)
- Notification service (notify mentioned users)
- Search index service (make tweet searchable)
- Analytics pipeline (count impressions)
Redis:
→ Caching layer for timelines
→ "Get timeline for user X" → check Redis first (O(1))
→ Cache miss → query Manhattan → store in Redis
INTERVIEW TAKEAWAY
Twitter kept ACID where it mattered (accounts, authentication — you can NEVER have two
users with the same username) and adopted NoSQL for high-volume, read-optimised data.
The fan-out problem (1 tweet → millions of timeline updates) is a classic system design
question. Know the trade-off between fan-out-on-write vs fan-out-on-read.
[Link] 6/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
CASE STUDY 4
The Problem
Uber had a unique constraint that the other companies didn't face:
[Link] 7/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
Uber Application
stores as blob
The JSON goes into a BLOB column — MySQL doesn't care about
the schema of the JSON. You can add any field anytime.
4. SHARDING by entity_id:
Each trip's data stays on ONE MySQL shard.
ACID transactions work because data is local to one shard.
[Link] 8/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
Uber realised their access pattern was always key-based ("get trip by trip_id"). They never
needed SQL's JOINs for trip data. So the lack of JOIN power wasn't a constraint. By storing
JSON in MySQL blob columns, they got NoSQL's flexibility while keeping MySQL's battle-
tested reliability. This shows that you can achieve NoSQL benefits on SQL if your access
patterns allow it.
INTERVIEW TAKEAWAY
Uber's approach teaches a critical lesson: always match the solution to the actual query
patterns, not the hype. They didn't need a fancy NoSQL cluster — they needed schema
flexibility + key lookups + ACID. MySQL with a JSON blob layer gave them all three. This is the
kind of nuanced thinking interviewers love.
Instagram SQL + NoSQL Users, relationships, Feeds, likes, Use BOTH — each
side-by-side photos (ACID) notifications (scale) for what it does best
[Link] 9/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
Side by side Wrong type → right type Build your own when MySQL underneath
[Link] 10/11
04/04/2026, 13:01 SQL vs NoSQL — Part 4: Real-World Case Studies
No company uses just one database at scale. They all use SQL for critical data + NoSQL for
scale. The interview answer is always: "It depends — and real systems use both."
[Link] 11/11
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
N O S Q L D E E P D I V E — D O C U M E N T S TO R E
DEFINITION
Imagine SQL as a spreadsheet — every row has the same columns, strictly enforced. Now
imagine MongoDB as a folder of papers. Each paper (document) can have different
information on it. One paper has name + email + phone. Another has name + address + age.
No one forces them to match. You just put whatever you need on each paper and file it in a
folder (collection).
[Link] 1/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
What Is a Document?
A document is a JSON-like object that holds all the data for one entity. Unlike SQL where you
split data across multiple tables and JOIN them, MongoDB encourages you to embed related
data inside one document.
{
"_id": ObjectId("507f1f77bcf86cd799439011"), // auto-generated unique ID
"name": "Amit Sharma",
"email": "amit@[Link]",
"age": 28,
"created_at": ISODate("2024-03-15T10:30:00Z"),
"state": "Maharashtra",
"pin": "400001"
},
In SQL, to show "Amit's profile with his address and orders," you'd need to JOIN 3 tables
(users + addresses + orders). That's 3 separate disk lookups and a computation to merge
them.
In MongoDB, ALL of Amit's data is in ONE document. One read from disk → you have
everything. This is why MongoDB is often faster for "get everything about this entity" queries.
What Is BSON?
MongoDB doesn't actually store raw JSON text. It converts JSON to BSON (Binary JSON) — a
binary-encoded format that's more efficient to store and faster to parse. BSON also supports
additional data types that JSON doesn't have: Date , ObjectId , Decimal128 , Binary ,
RegExp .
You write JSON in your application code, but MongoDB stores BSON on disk. This is
transparent — you never need to think about the conversion.
[Link] 3/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
Every document MUST have an "_id" field. If you don't provide one,
MongoDB auto-generates an ObjectId:
ObjectId("507f1f77bcf86cd799439011")
├────┤├──┤├──┤├────────┤
│ │ │ │
│ │ │Counter (3 bytes) — unique within same second
└─
│ │ └────── Process ID (2 bytes, since v3.4: random)
│ └─────────── Machine ID (3 bytes, since v3.4: random)
└───────────────── Timestamp (4 bytes) — seconds since epoch
The storage engine is the component that manages how data is stored on disk and read into
memory. It's the lowest layer — everything else (queries, indexes, replication) sits on top of it.
Since MongoDB 3.2, the default storage engine is WiredTiger.
1. DOCUMENT-LEVEL LOCKING
In older MongoDB (MMAPv1 engine): collection-level lock.
One writer blocks ALL other writers on the same collection.
2. COMPRESSION
WiredTiger compresses data on disk using:
[Link] 4/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
4. IN-MEMORY CACHE
WiredTiger maintains a cache in RAM (default: 50% of RAM).
Hot data stays in memory → reads don't hit disk.
Eviction policies manage what stays and what gets flushed.
5. B-TREE INDEXES
Indexes are stored as B-Tree structures (similar to B+ Tree).
Default index on _id is created automatically.
Additional indexes must be created manually.
[Link] 5/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
MongoDB uses its own query language (not SQL). Here are the core operations:
[Link] 6/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
INSERT OPERATIONS
// Find with OR
[Link]({ $or: [{ city: "Mumbai" }, { age: { $gt: 30 } }] })
[Link] 7/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
// COUNT
[Link]({ city: "Mumbai" })
UPDATE OPERATIONS
// INCREMENT a number
[Link](
{ _id: ObjectId("507f1f77bcf86cd799439011") },
{ $inc: { age: 1 } } // age = age + 1
)
// PUSH to an array
[Link](
{ email: "amit@[Link]" },
{ $push: { tags: "verified" } } // add "verified" to tags array
)
[Link] 8/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
{ email: "new@[Link]" },
{ $set: { name: "New User", age: 20 } },
{ upsert: true } // creates document if not found
)
DELETE OPERATIONS
MongoDB's equivalent of SQL's GROUP BY , HAVING , JOIN , and subqueries — all in one.
Data flows through a series of stages, each transforming the data. Like a factory assembly line
where each station does one operation.
// SQL: SELECT city, COUNT(*) as count FROM users GROUP BY city ORDER BY count DESC
[Link]([
{ $group: { _id: "$city", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
// SQL: SELECT city, AVG(age) FROM users WHERE age > 20 GROUP BY city HAVING COUNT(*) >
[Link]([
{ $match: { age: { $gt: 20 } } }, // Stage 1: WHERE age > 20
{ $group: { // Stage 2: GROUP BY city
[Link] 9/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
_id: "$city",
avgAge: { $avg: "$age" },
count: { $sum: 1 }
}},
{ $match: { count: { $gt: 5 } } }, // Stage 3: HAVING count > 5
{ $sort: { avgAge: -1 } } // Stage 4: ORDER BY avgAge DESC
])
5 Indexing in MongoDB
Just like SQL databases, MongoDB uses B-Tree indexes to speed up queries. Without indexes,
MongoDB must scan every document in a collection (collection scan). With indexes, it jumps
directly to matching documents.
[Link] 10/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
1. Same left-prefix rule as SQL: compound index {a:1, b:1, c:1} works for queries on a ,
a+b , a+b+c — NOT b alone.
2. Each index slows down writes (same trade-off as SQL).
3. MongoDB has a 64 index limit per collection.
4. Multikey indexes on arrays can get very large — index each array element.
5. TTL indexes are amazing for session data, cache entries, and logs — auto-cleanup!
[Link] 11/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
A replica set is a group of MongoDB servers that maintain the same data. One server is the
primary (handles all writes), and the others are secondaries (receive copies of the data). If the
primary fails, a secondary is automatically elected as the new primary — automatic failover.
Application
PRIMARY
All WRITES go here
SECONDARY 1 SECONDARY 2
Async replication from Primary Async replication from Primary
Can serve reads (read preference) Automatic failover if Primary dies
AUTOMATIC FAILOVER:
1. Primary goes down (crash, network issue)
2. Secondaries detect primary is unresponsive (heartbeat timeout)
3. Secondaries hold an ELECTION
4. One secondary is PROMOTED to new primary
5. Application driver automatically reconnects to new primary
6. Total failover time: typically 10-30 seconds
READ SCALING:
Route read queries to secondaries to spread the load.
But reads from secondaries may return SLIGHTLY STALE data
(async replication lag — usually milliseconds to seconds).
When your data is too large for one server (or write throughput exceeds one server's
capacity), you shard — split data across multiple servers. MongoDB has built-in sharding,
unlike SQL databases where sharding is an afterthought.
Application
1. mongos (Router)
→ Your app connects to mongos (not directly to shards)
→ mongos knows which shard has which data
→ Routes queries to the correct shard(s)
→ Multiple mongos instances for load balancing
[Link] 13/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
STRATEGIES:
• Hashed shard key: hash(user_id) → even write distribution
But range queries on user_id now span all shards.
• Range shard key: user_id ranges → range queries are efficient
But risk of hot shards if distribution is uneven.
• Compound shard key: { region: 1, user_id: 1 }
→ Queries for one region go to one shard group
[Link] 14/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
[Link] 15/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
A single MongoDB document cannot exceed 16 MB. This means you can't embed unlimited
data inside one document. If an array (like comments on a post) can grow unboundedly,
eventually the document hits 16MB and writes fail. For unbounded arrays, use a separate
collection with a reference — don't embed.
EMBED when: data is always accessed together, data is bounded (won't grow forever), one-to-
few relationship (user has 1-3 addresses).
REFERENCE (separate collection) when: data is accessed independently, data can grow
unboundedly (user has millions of comments), many-to-many relationship (students ↔
courses).
[Link] 16/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
→ Data has nested structures (JSON-like) → You need strong consistency on every
read
→ Real-time analytics with aggregation
pipeline → Financial/banking data (use SQL + ACID)
→ Mobile/web apps with JSON APIs → Time-series metrics at extreme scale (use
Cassandra/InfluxDB)
→ IoT data with varying sensor schemas
→ Team has zero NoSQL experience
eBay Product catalog, search Flexible product schemas (electronics vs clothing have
suggestions different fields). Billions of listings.
Forbes Content management Articles have varying structures (text, video, galleries).
system Schema flexibility is critical.
Adobe User data platform, Handles 100B+ events/day. Schema-less events with
analytics varying properties.
Uber Geospatial data, trip MongoDB's geospatial indexes for finding nearby drivers.
matching Location data changes constantly.
Coinbase Cryptocurrency portfolio Rapidly evolving data models as new cryptocurrencies and
data features are added.
EA Player profiles, game state Each game has different data structures. Player state
Games varies widely between games.
Toyota Connected vehicle data IoT sensor data from vehicles with varying sensor
configurations per model.
[Link] 17/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
Notice the common thread: every company chose MongoDB because their data was naturally
document-shaped with varying fields. A product listing for a laptop has "RAM, CPU, GPU"
fields. A product listing for a shirt has "size, color, material" fields. In SQL, you'd need either a
massive table with hundreds of nullable columns or complex EAV (Entity-Attribute-Value)
patterns. In MongoDB, each document simply has the fields it needs.
When my data is naturally document-shaped with nested structures (user profiles, product
catalogs), when the schema evolves frequently (startup, rapid iteration), when I need built-in
horizontal sharding for scale, and when my primary access pattern is key-based lookups rather
than complex multi-table JOINs. I'd choose PostgreSQL when I need ACID transactions across
multiple entities, complex relational queries, or the data has many-to-many relationships.
Through replica sets — a group of MongoDB instances maintaining the same data. One
primary handles all writes, secondaries replicate asynchronously. If the primary fails, an
automatic election promotes a secondary within 10-30 seconds. The driver automatically
reconnects. For read scaling, you can route reads to secondaries using read preferences.
Q3: "HOW WOULD YOU HANDLE A USE CASE WHERE A DOCUMENT KEEPS GROWING ( E.G.,
COMMENTS ON A POST)?"
I would NOT embed comments inside the post document because it can grow unboundedly
and hit the 16MB document limit. Instead, I'd use a separate comments collection with a
reference: each comment has a post_id field. I'd create an index on { post_id: 1,
created_at: -1 } for efficient retrieval. This is the "reference" pattern vs the "embed"
pattern — use embedding for bounded, always-accessed-together data, and referencing for
unbounded or independently-accessed data.
A good shard key has high cardinality (many distinct values for even distribution), even write
distribution (writes don't all go to one shard), and query isolation (most queries can be routed
[Link] 18/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
to a single shard). Example: user_id is often a good shard key. A bad shard key is something
monotonically increasing like created_at because all new writes go to the latest shard,
creating a hot spot.
Yes, since MongoDB 4.0 (2018), it supports multi-document ACID transactions across replica
sets, and since 4.2, across sharded clusters. However, transactions are slower than SQL
transactions and should be used sparingly. MongoDB's philosophy is to design your data
model so that most operations affect a single document (which is always atomic) and only use
multi-document transactions when absolutely necessary.
Embed when: the data is always read together, the relationship is 1-to-few (user has 2-3
addresses), the embedded data is bounded and won't grow forever.
Reference when: the data is accessed independently, the relationship is 1-to-many or many-
to-many, the array could grow unboundedly (comments, orders), or the referenced data
changes frequently and you don't want to update it everywhere.
CORE CONCEPTS
Database → Collection (table) → Document (row) → Field (column). _id = auto-generated
ObjectId (primary key). Embed related data inside documents.
STORAGE ENGINE
WiredTiger: document-level locking, compression (Snappy/Zstd), journal (WAL for durability),
in-memory cache (50% RAM), B-Tree indexes.
QUERIES
find() , insertOne/Many() , updateOne/Many() , deleteOne/Many() . Aggregation pipeline:
$match → $group → $sort → $project → $lookup (JOIN).
[Link] 19/20
04/04/2026, 13:14 MongoDB — Complete Deep Dive from Zero to Expert
INDEXES
B-Tree indexes. Single, compound (left-prefix rule!), unique, text, TTL (auto-expire), partial,
multikey (arrays). 64 index limit per collection.
SCALING
Replica Sets: 1 primary + N secondaries. Automatic failover. Read scaling via secondaries.
Async replication.
Sharding: Built-in. mongos router → config servers → shards (each a replica set). Shard key =
most critical decision. Hashed (even writes) vs ranged (efficient range queries).
EMBED VS REFERENCE
Embed: always accessed together, bounded, 1-to-few. Reference: independent access,
unbounded growth, many-to-many. 16MB doc limit!
WHEN TO USE
Use: document-shaped data, evolving schema, horizontal scale, key-based lookups, nested
data, CMS, catalogs, mobile apps.
Don't use: complex JOINs, multi-doc ACID critical, highly relational, financial/banking, graph
traversals.
COMPANIES
eBay (catalogs), Forbes (CMS), Adobe (analytics), Uber (geospatial), Coinbase (crypto), EA
Games (player state), Toyota (IoT).
[Link] 20/20
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
N O S Q L D E E P D I V E — W I D E - C O L U M N S TO R E
DEFINITION
Imagine a postal system with hundreds of post offices across a country. When you send a
letter (write), it goes to the nearest post office — no single central office handles everything.
Each post office stores letters for its local area. If one post office burns down, the others still
work. Letters are eventually delivered to all relevant offices (eventual consistency). No single
post office is the "boss" — they're all equal (peer-to-peer). That's Cassandra — no single
master, every node is equal, writes go to the nearest available node.
[Link] 1/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Read Speed Fast (B+ Tree) Fast (B-Tree) Moderate (multi-level reads)
Query Power Rich JOINs, SQL Aggregation pipeline Limited (no JOINs, restricted
WHERE)
Availability Single point of failure Automatic failover Always available (no master)
Best For Complex queries, Flexible docs, Massive writes, time-series, IoT
ACID catalogs
[Link] 2/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Cassandra's data model looks like SQL tables on the surface, but underneath it works
completely differently. The partition key determines which node stores the data. The
clustering key determines the sort order within a partition. Getting this right is the single most
critical design decision.
[Link] 3/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
RESULT:
Partition: channel_id = "gaming-chat"
┌──────────────────────────────────────────────────────┐
│ message_id (sorted!) │ author │ content │
├──────────────────────┼─────────┼─────────────────────┤
│ 2024-03-15T09:00:01 │ Amit │ "Hello everyone!" │
│ 2024-03-15T09:00:05 │ Sara │ "Hey Amit!" │
│ 2024-03-15T09:01:12 │ Rahul │ "Good morning" │
│ 2024-03-15T09:03:45 │ Amit │ "How's it going?" │
│ ...millions more... │ │ │
└──────────────────────┴─────────┴─────────────────────┘
All sorted by time within this partition → range reads are FAST
All data with the same partition key lives on the same node. If a partition grows too large
(100MB+), it becomes a hot spot — one node handles disproportionate traffic while others are
idle. This is why Discord uses (channel_id, bucket) — the bucket splits very active
channels into time-based chunks so no single partition gets too big.
[Link] 4/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Cassandra uses a Log-Structured Merge Tree (LSM Tree) instead of a B+ Tree. This is the
fundamental reason Cassandra writes are so fast. In a B+ Tree (SQL/MongoDB), writes require
finding the right position on disk and updating in-place — this means random disk I/O. In an
LSM Tree, writes go to an in-memory table first, then get flushed sequentially to disk.
Sequential writes are 100x faster than random writes.
[Link] 5/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Query: SELECT * FROM messages WHERE channel_id = 'abc' AND message_id = 'xyz';
[Link] 6/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
B+ Tree (SQL/MongoDB): Reads are fast (sorted tree, one lookup). Writes are slower (find
position, update in-place, random I/O). Read-optimised.
LSM Tree (Cassandra): Writes are fast (append to log + RAM, sequential I/O). Reads are
slower (check memtable + multiple SSTables). Write-optimised.
This is the fundamental trade-off. Cassandra chose to optimise for writes because its target
use cases (IoT, feeds, messaging) are write-heavy.
PEER-TO-PEER ARCHITECTURE
Unlike SQL (single master) or MongoDB (primary + secondaries), Cassandra uses a peer-to-
peer architecture. Every node is equal — there is no master, no primary, no leader. Any node
[Link] 7/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
can accept reads and writes. If one node goes down, the others continue serving traffic
seamlessly. No failover election needed because there's nothing to fail over FROM.
Node A
Node F is DOWN
Other nodes handle its
data via replication → no downtime!
DOWN! ✗ Token: 25-49
Node F Node B
Node E Node C
Token: 100-124 Token: 50-74
Node D
Token: 75-99
EXAMPLE:
Node A: tokens 0-24 Node D: tokens 75-99
Node B: tokens 25-49 Node E: tokens 100-124
Node C: tokens 50-74 Node F: tokens 125-149
MULTI-DATACENTER REPLICATION:
CREATE KEYSPACE myapp WITH replication = {
'class': 'NetworkTopologyStrategy',
'us-east': 3, -- 3 copies in US East
'eu-west': 3, -- 3 copies in EU West
'ap-south': 3 -- 3 copies in Asia
};
→ Data automatically replicated across 3 continents
→ Local reads are fast (nearby datacenter)
→ If entire US datacenter goes down, EU and Asia still work
Unlike SQL (always strong) or most NoSQL (always eventual), Cassandra lets you choose per-
query how consistent you want the response to be. You control the trade-off between
consistency and latency/availability for each individual read and write operation.
[Link] 9/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
[Link] 10/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
CQL looks like SQL but has strict constraints on what you can query. This is by design —
Cassandra trades query flexibility for performance.
USE myapp;
-- CREATE TABLE
CREATE TABLE messages (
channel_id UUID,
message_id TIMEUUID,
author TEXT,
content TEXT,
created_at TIMESTAMP,
PRIMARY KEY (channel_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC); -- newest first
-- INSERT
INSERT INTO messages (channel_id, message_id, author, content, created_at)
VALUES (uuid(), now(), 'Amit', 'Hello world!', toTimestamp(now()));
-- DELETE
DELETE FROM messages
WHERE channel_id = some-uuid AND message_id = some-timeuuid;
[Link] 11/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
The rule: Model your tables based on your queries, NOT based on your entities. In SQL you
model entities then figure out queries. In Cassandra you start with queries and design tables to
serve them.
In Cassandra, you create one table per query pattern. If you have 5 different ways to query the
same data, you create 5 tables — each optimised for one query. This means data duplication
is normal and expected. The trade-off: more disk space + write amplification, but reads are
always fast.
QUERIES WE NEED:
Q1: Get all messages in a channel (sorted by time)
Q2: Get all messages by a specific user (across all channels)
Q3: Get message count per channel
-- Table for Q2: messages by user (SAME DATA, different partition key)
CREATE TABLE messages_by_user (
user_id UUID,
message_id TIMEUUID,
channel_id UUID, content TEXT,
[Link] 12/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Why is it linear?
→ No master = no bottleneck
→ Each node handles its own partition range
→ Adding a node = existing nodes give it some token ranges
→ Data automatically rebalances in the background
→ No downtime during scaling!
COMPARED TO SQL:
SQL: Add a server → manually set up sharding, update routing
logic, migrate data, test, pray → days/weeks of work
[Link] 13/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
→ LSM Tree = writes go to RAM then → Reads may hit multiple SSTables (pre-
sequential disk compaction)
→ No locks, no contention on writes → No JOINs — must denormalise for each
→ Peer-to-peer = writes distributed across all query
nodes → Key cache + row cache help for hot data
→ Millions of writes/sec on commodity → Compaction improves read performance
hardware over time
→ Examples: IoT sensors, activity feeds, logs, → For read-heavy with complex queries →
messaging, metrics, event sourcing use MongoDB or SQL
→ Real-world: Instagram (billions of → For read-heavy with simple key lookups →
likes/day), Discord (billions of messages) Cassandra works
[Link] 14/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
→ Always available — survives node/rack/DC → No ad-hoc queries — must plan all queries
failures upfront
→ Time-series optimised (clustering by time) → Tombstones — deletes create markers that
→ TTL support — auto-expire data slow reads
→ Proven at massive scale (Apple: 150K+ → Compaction — uses CPU and I/O in
nodes) background
→ Operational complexity — tuning, repair,
monitoring
→ Steep learning curve for developers from
SQL background
When you DELETE data in Cassandra, it doesn't immediately remove it. Instead, it writes a
tombstone — a marker that says "this data is deleted." During compaction, tombstones are
eventually cleaned up. But until then, reads must scan through tombstones, which slows down
reads. If you delete a lot of data frequently, tombstones can accumulate and cripple read
performance. This is why Cassandra is best for append-heavy workloads where deletes are
rare.
[Link] 15/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Apple iCloud, Siri, Maps, iTunes 150,000+ Largest known deployment. Multi-DC
nodes replication for global availability.
Netflix User viewing history, 2,500+ nodes Write-heavy viewing events. Multi-
recommendations region for global streaming.
Uber Driver/rider location, trip Millions Real-time location writes. Multi-DC for
data trips/day global operations.
Spotify User activity, playlists Hundreds of Write-heavy user events. Playlist data
nodes with flexible schema.
Twitter/X Timeline storage, analytics Massive scale Timeline fan-out writes. Append-only
tweets.
Every company using Cassandra has the same characteristics: write-heavy workload (feeds,
events, messages, metrics), time-series or append-only data, simple key-based access
patterns, and multi-region deployment. None of them use Cassandra for complex relational
queries or heavy JOINs — they pair it with SQL or MongoDB for those needs.
[Link] 16/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
Peer-to-peer architecture with consistent hashing. Every node is equal — any node can
accept reads and writes. Data is replicated to multiple nodes (RF=3 typically). If one node dies,
others serve its data from replicas. No election, no failover delay. The ring topology with
consistent hashing distributes data evenly and makes adding/removing nodes seamless.
Use QUORUM for both reads and writes. With RF=3, QUORUM means 2 out of 3 nodes must
respond. Write QUORUM (2) + Read QUORUM (2) = 4 > RF (3), which satisfies the formula W
+ R > RF for strong consistency. This means any read will always see the latest write. The
trade-off is higher latency compared to consistency level ONE.
A good partition key has high cardinality (many distinct values for even distribution), avoids
hot partitions (no one value dominates), and matches query patterns (queries should include
the partition key). Example: user_id for user-specific data. Bad example: country (few
values = uneven distribution) or created_date (all today's writes go to one partition).
Q5: "WHY DID DISCORD MIGRATE FROM MONGODB TO CASSANDRA FOR MESSAGES?"
Messages are append-only (never updated), always queried by time range within a channel,
and need predictable low latency at massive scale. MongoDB's B-Tree storage wasn't
optimised for this pattern — read latency degraded at scale. Cassandra's LSM Tree handles
append-heavy writes better, and clustering keys provide natural time-ordering within
partitions. Partition key (channel_id, bucket) prevents any single partition from growing too
large.
[Link] 17/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
When you delete data in Cassandra, it doesn't immediately remove it — it writes a tombstone
marker. Tombstones are cleaned up during compaction, but until then, reads must scan
through them. If you delete a lot of data frequently, tombstones accumulate and slow down
reads significantly. Mitigation: use TTL for time-based auto-expiry instead of explicit deletes,
tune compaction strategy, avoid frequent delete-heavy patterns.
DATA MODEL
Keyspace → Table → Partitions → Rows. Partition Key = which node stores data. Clustering
Key = sort order within partition. Model tables per query, not per entity. Data duplication is
normal.
READ PATH
Memtable → Bloom Filters (skip irrelevant SSTables) → Key Cache → Partition Index → SSTable
→ Merge results. Reads check multiple SSTables (slower than writes).
DISTRIBUTION
Consistent hashing ring. hash(partition_key) → token → node. Replication Factor (RF=3): 3
copies on 3 nodes. Multi-DC: NetworkTopologyStrategy. Add nodes = linear scaling, no
downtime.
TUNABLE CONSISTENCY
[Link] 18/19
04/04/2026, 13:39 Apache Cassandra — Complete Deep Dive from Zero to Expert
ONE (fastest, may be stale) → QUORUM (majority, balanced) → ALL (strongest, slowest). Strong
consistency: W + R > RF . QUORUM + QUORUM with RF=3 = strong.
CQL
Looks like SQL but no JOINs, no arbitrary WHERE, must include partition key. CREATE TABLE,
INSERT, SELECT, UPDATE, DELETE, TTL. Aggregation limited.
TRADE-OFFS
Strengths: Extreme writes, linear scale, no SPOF, multi-DC, tunable consistency, time-series,
TTL.
Weaknesses: No JOINs, limited queries, reads slower, tombstone problem, data modelling is
hard, operational complexity, steep learning curve.
WHEN TO USE
Use: Write-heavy, time-series, IoT, feeds, messaging, metrics, multi-region, always-on. Don't
use: Complex JOINs, ad-hoc queries, heavy deletes, small data, relational data, read-heavy with
aggregations.
COMPANIES
Apple (150K nodes), Netflix, Instagram, Discord, Uber, Spotify, Twitter. All use it for write-heavy,
append-only, time-series data.
[Link] 19/19
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
N O S Q L D E E P D I V E — G R A P H DATA B A S E
DEFINITION
Imagine a whiteboard with sticky notes and strings. Each sticky note is a person (node). You
draw a string between two notes to show they're friends (relationship). The string itself can
have a label — "friends since 2020" or "works with." To find "friends of friends of Amit," you
just follow the strings — you don't need to look up anything in a table. That's how Neo4j works.
Following connections is instant because the connections are physically stored alongside the
data.
Why Graph Databases Exist — The Problem SQL Can't Solve Efficiently
PERFORMANCE:
Level 1: fast
Level 2: slow (1 JOIN on 1B rows)
Level 3: very slow (2 JOINs)
Level 4: unbearably slow (3 JOINs)
Level 5: times out or crashes
PERFORMANCE:
Level 1: instant
Level 2: instant
Level 3: instant
Level 4: instant
Level 5: STILL instant!
[Link] 2/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
SQL: Relationship traversal time depends on the total size of the table. 1B rows → every JOIN
scans parts of 1B rows. Gets exponentially slower with depth.
Neo4j: Relationship traversal time depends on the number of connections traversed, NOT the
total database size. 10 users or 10 billion users — traversing Amit's 50 friends takes the same
time. This is called index-free adjacency — the killer feature of graph databases.
Before diving into Neo4j specifics, you need to understand three building blocks of any graph:
[Link] 3/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
VISUAL EXAMPLE:
since: "2022"
:Person
LEGEND
:FOLLOWS name: "Priya"
:Person age: 25
Node — an entity (person, product)
name: "Amit"
age: 28 Relationship — connection + direction
amount: 5000
Label — :Person, :Product (node type)
:PURCHASED
:LIVES_IN Properties — key:value on nodes/edges
:Product Type — :FOLLOWS, :PURCHASED (edge type)
name: "Laptop"
Relationships ALWAYS have direction
brand: "Dell"
:City
Mumbai
In SQL, to find related records you look up an index, scan a table, and join. In Neo4j, each node
physically stores pointers to its adjacent nodes. To traverse from Amit to his friends, Neo4j
doesn't consult any index — it follows the direct pointer stored on Amit's node. This is called
[Link] 4/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
index-free adjacency — the reason graph traversals are O(1) per hop regardless of database
size.
4. LABEL STORE
→ Maps label names (:Person, :Product) to internal IDs
SQL approach:
1. Scan friendships table (could be billions of rows)
2. Filter where user_id = 'Amit'
3. Time: proportional to TABLE SIZE
Neo4j approach:
1. Go to Amit's node record (direct address, O(1))
2. Read first_rel_id → pointer to first relationship
[Link] 5/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
Some databases add a "graph layer" on top of SQL (like Amazon Neptune on SQL tables). They
store graph data in regular tables and simulate traversals with JOINs. Neo4j is a native graph
database — the storage engine itself is designed for nodes and relationships. This is why
Neo4j traversals are orders of magnitude faster than graph-on-SQL solutions for deep
traversals (3+ levels).
Cypher is Neo4j's declarative query language. It uses ASCII art to represent graph patterns —
you literally draw the pattern you're looking for.
[Link] 6/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
// Create a node
CREATE (:Person {name: "Amit", age: 28, city: "Mumbai"})
[Link] 7/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
// Update a property
MATCH (a:Person {name: "Amit"})
SET [Link] = 29, [Link] = true
// Add a label
MATCH (a:Person {name: "Amit"})
SET a:PremiumUser
// Delete a relationship
MATCH (a:Person {name: "Amit"})-[r:FOLLOWS]->(p:Person {name: "Priya"})
DELETE r
5 Indexing in Neo4j
IMPORTANT DISTINCTION
Neo4j has two types of lookups: (1) Finding a starting node (WHERE name = "Amit") — this
uses indexes, just like SQL. (2) Traversing from that node (following relationships) — this uses
index-free adjacency (direct pointers), no index needed. You only need indexes for the initial
lookup to find where to start traversing.
[Link] 9/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
Unlike Cassandra (linear horizontal scaling) or MongoDB (built-in sharding), Neo4j is harder to
scale horizontally. Graph data is inherently interconnected — if you split the graph across
servers, traversals that cross server boundaries become network hops instead of local pointer
follows, which destroys the performance advantage.
[Link] 10/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
Application
writes reads
[Link] 11/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
→ Schema optional but constraints available → Not for tabular data (use SQL)
[Link] 12/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
→ Visual browser for exploring data → Learning curve for Cypher if coming from
SQL
→ Aggregations not as powerful as SQL's
GROUP BY
[Link] 13/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
LinkedIn Connection suggestions, Social graph traversal: "who knows who" at 3-4 levels
"People You May Know," deep. SQL JOINs would be impossibly slow at 900M+
profile viewers users.
eBay Shipping route optimisation, Finding optimal routes through delivery network graph.
delivery network Shortest path algorithms built into Neo4j.
Walmart Real-time recommendation "Customers who bought X also bought Y" requires
engine traversing purchase relationships across millions of
customers.
NASA Knowledge graph for space Connecting lessons learned, equipment, missions,
mission data failures across decades of data. Relationships between
data points are the value.
Airbnb Trust and safety, fraud Detecting fake reviews by finding circular patterns:
prevention user A reviews B, B reviews C, C reviews A. Graph
pattern matching is perfect for this.
UBS Bank Regulatory compliance, risk Tracing exposure: "If company X defaults, which
analysis portfolios are affected?" Requires traversing ownership
and investment chains.
Every company using Neo4j has one thing in common: the value is in the connections, not
just the data. LinkedIn doesn't just store users — it navigates the social graph. Panama Papers
didn't just store documents — it exposed hidden networks. Walmart doesn't just store products
— it traverses purchase patterns. If your app's core value comes from navigating
relationships between entities, Neo4j is the right choice.
[Link] 14/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
Q1: "WHY WOULD YOU USE NEO4J INSTEAD OF SQL FOR RELATIONSHIP-HEAVY DATA?"
Each node in Neo4j physically stores pointers to its relationships, and each relationship stores
pointers to its start/end nodes and the next relationship. To traverse from one node to its
neighbors, you follow these pointers directly — no index lookup, no table scan. This means
traversal time is proportional to the number of relationships traversed, not the total size of the
graph. It's the reason graph databases are orders of magnitude faster than SQL for
relationship-heavy queries.
Use collaborative filtering via graph traversal: (1) Start at the target user node. (2) Find
products they've purchased. (3) Find OTHER users who purchased the same products. (4) Find
what ELSE those users purchased. (5) Filter out products the target user already has. (6) Rank
by how many "similar users" purchased each recommendation. This is a natural graph
traversal — follow PURCHASED edges, then reverse-follow PURCHASED edges. In Cypher it's
about 5 lines. In SQL it would be multiple complex JOINs.
Yes — Neo4j is fully ACID compliant, which is unusual for NoSQL databases. Every read and
write operation happens within a transaction. Multiple operations can be grouped into a single
transaction that either fully commits or fully rolls back. This makes Neo4j reliable for use cases
[Link] 15/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
like financial fraud detection where data integrity is critical. However, transactions are limited
to a single database instance (not distributed transactions across a cluster).
When the data is tabular with simple relationships (SQL is simpler and more mature), when I
need massive write throughput (Cassandra's peer-to-peer architecture handles this better),
when the queries are simple key-value lookups (Redis is faster), when the data is document-
shaped (MongoDB is more natural), or when the dataset is so large it can't fit on one server
and doesn't have natural graph boundaries for sharding.
CORE CONCEPTS
Nodes = entities (:Person, :Product). Relationships = connections (:FOLLOWS, :PURCHASED).
Both have labels/types and properties (key-value). Relationships always have direction.
STORAGE
Fixed-size records: Node Store, Relationship Store, Property Store. Relationships form doubly
linked lists from each node. WiredTiger-like caching — best when graph fits in RAM.
SCALING
Vertical first (more RAM). Read replicas for read scaling (Causal Cluster). Fabric for federated
queries. Graph sharding is HARD — cutting relationships = network hops = slow. Write scaling is
limited (single primary).
[Link] 16/17
04/04/2026, 13:39 Neo4j — Complete Deep Dive from Zero to Expert
READ VS WRITE
Read-heavy = sweet spot. Traversals are instant. Add read replicas. Write-heavy = NOT ideal.
Single primary bottleneck. Pair with Cassandra/Kafka for writes, batch into Neo4j.
WHEN TO USE
Use: Social graphs, recommendations, fraud detection, knowledge graphs, shortest paths,
access control, network topology.
Don't use: Tabular data (SQL), massive writes (Cassandra), key-value (Redis), documents
(MongoDB), time-series (InfluxDB), data too large for one server.
COMPANIES
LinkedIn (social graph), eBay (routing), Walmart (recommendations), NASA (knowledge graph),
Panama Papers (investigative journalism), Airbnb (fraud), UBS (risk).
INTERVIEW GOLD
"Friends of friends" in SQL: self-JOINs → exponentially slower with depth. In Neo4j: follow
pointers → constant time per hop. 3 levels in 3ms whether DB has 1K or 1B nodes.
[Link] 17/17
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
N O S Q L D E E P D I V E — I N - M E M O RY DATA B A S E / K E Y-VA L U E S TO R E
DEFINITION
Redis stands for REmote DIctionary Server. It is an in-memory data structure store that can be
used as a database, cache, message broker, and streaming engine. The core idea: all data
lives in RAM (not on disk), making every operation happen in microseconds instead of
milliseconds. It supports multiple data structures beyond simple key-value — strings, lists, sets,
sorted sets, hashes, streams, and more.
Imagine you need a document. A disk-based database (MySQL, MongoDB) is like walking to a
filing cabinet in another room, opening the drawer, finding the folder, pulling the document, and
walking back — takes seconds. Redis is like having the document already on your desk, right
in front of you — you just look down and read it — takes a fraction of a second.
That's the difference between disk I/O (~5-10ms) and RAM access (~0.1μs). RAM is roughly
100,000x faster than disk.
[Link] 1/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
Most people think Redis is just SET key value / GET key . That's like saying a smartphone is
just a phone. Redis provides 8 rich data structures, each with atomic operations built in. This
is why Redis can replace entire application-level data logic — not just caching.
[Link] 2/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
USE CASES: Caching, counters, rate limiters, distributed locks, session tokens
USE CASES: Activity feeds, notification lists, message queues, recent items
USE CASES: Tags, unique visitors, mutual friends, online users, voting
ZADD leaderboard 9500 "Amit" 8700 "Priya" 9200 "Sara" 7800 "Rahul"
[Link] 4/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
USE CASES: Daily active users, feature flags, online status, A/B test groups
USE CASES: Unique page views, unique search queries, cardinality estimation
[Link] 5/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
USE CASES: Event sourcing, activity streams, real-time analytics, chat messages
Redis processes all commands in a single thread using an event loop (like [Link]). This
sounds slow but is actually genius: no locks, no context switching, no race conditions. Since
everything is in RAM and operations are simple (O(1) or O(log N)), a single thread can process
100,000+ operations per second. Multithreading would add complexity without much benefit
because the bottleneck is network I/O, not CPU.
If all data is in RAM, doesn't a power failure or crash lose everything? No — Redis offers two
persistence mechanisms to save data to disk. Most production deployments use both.
[Link] 7/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
Pseudocode:
data = [Link]("user:1001")
if data is None:
data = [Link]("SELECT * FROM users WHERE id = 1001")
[Link]("user:1001", 3600, data) // cache for 1 hour
return data
PATTERN 2: WRITE-THROUGH
1. App writes to Redis AND database simultaneously
2. Every read is always from Redis (always fresh!)
PATTERN 4: REFRESH-AHEAD
1. Proactively refresh cache BEFORE TTL expires
2. Background job refreshes frequently-accessed keys
[Link] 8/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
10 USE CASES WHERE REDIS IS THE PRIMARY SYSTEM, NOT JUST A CACHE
1. SESSION STORE
Hash per session: HSET session:abc123 user_id 1001 role "admin"
Set TTL: EXPIRE session:abc123 3600
→ Faster than DB sessions. Shared across app servers.
2. RATE LIMITER
INCR rate:user:1001:minute → increment counter
EXPIRE rate:user:1001:minute 60
If count > 100: reject request (100 req/min limit)
3. REAL-TIME LEADERBOARD
Sorted Set: ZADD leaderboard 9500 "player1"
Top 10: ZREVRANGE leaderboard 0 9 WITHSCORES
→ Millions of players, instant ranking updates.
[Link] 9/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
4. DISTRIBUTED LOCK
SET lock:order:555 "server1" NX EX 30
→ NX = set only if not exists. EX = auto-expire in 30s.
→ Prevents two servers from processing the same order.
5. PUB/SUB MESSAGING
SUBSCRIBE channel:notifications
PUBLISH channel:notifications "New order received!"
→ Real-time events between services. Like a mini Kafka.
6. REAL-TIME ANALYTICS
Bitmaps for DAU: SETBIT active:2024-03-15 1001 1
HyperLogLog for unique visitors: PFADD visits "user1" "user2"
→ Billions of events, 12KB of memory.
7. GEOSPATIAL
GEOADD restaurants 72.8777 19.0760 "Pizza Place"
GEORADIUS restaurants 72.88 19.08 5 km COUNT 10
→ Find 10 nearest restaurants within 5km.
8. MESSAGE QUEUE
LPUSH queue:emails "send welcome email to user 1001"
BRPOP queue:emails 30 → worker blocks until new task arrives
9. AUTOCOMPLETE / TYPEAHEAD
Sorted Set with prefix matching.
User types "am" → ZRANGEBYLEX suggestions "[am" "[am\xff" LIMIT 0 10
Architecture:
Server A ──PUBLISH──→ [ REDIS ] ──NOTIFY──→ Server B
[Link] 10/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
──NOTIFY──→ Server C
──NOTIFY──→ Server D
LIMITATIONS:
→ Fire-and-forget: if subscriber is disconnected, message is LOST
→ No persistence: messages are NOT stored
→ For durable messaging: use Redis Streams instead of Pub/Sub
→ For production message queues: consider Kafka or RabbitMQ
┌──────────────┐
│ MASTER │ ← All writes go here
│ (read+write) │
└──────┬───────┘
│ async replication
┌────┴────┐
↓ ↓
┌──────────┐ ┌──────────┐
│ REPLICA 1│ │ REPLICA 2│ ← Read-only copies
│ (read) │ │ (read) │ Serve read traffic
└──────────┘ └──────────┘
IF MASTER DIES:
1. Sentinels detect master is down (quorum vote)
2. Sentinels elect a replica to become new master
3. Other replicas reconfigure to follow new master
4. Clients automatically reconnect to new master
→ Failover: 10-30 seconds
Application
ADDING A NODE:
→ Add Master 4. Redistribute some slots to it.
→ Data for those slots migrates automatically.
→ Client libraries auto-discover new topology.
LIMITATIONS:
→ Multi-key operations only work if all keys are in SAME slot
[Link] 12/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
→ All reads from RAM → microsecond latency → All writes to RAM → equally fast
→ Add read replicas for horizontal read → Redis Cluster shards writes across masters
scaling → Counters: INCR is atomic single-threaded
→ Cache-aside pattern: 95%+ cache hit ratio = no locks
→ Sorted sets for leaderboards: O(log N) → Streams: append-only log for high-
reads throughput events
→ Examples: caching, session stores, → Examples: counters, rate limiting, metrics
leaderboards → Real-world: Instagram uses Redis counters
→ Real-world: Twitter uses Redis for timeline for likes
caching
→ Atomic operations — INCR, LPUSH, etc. → Dataset must fit in RAM — can't store 10TB
are thread-safe → No complex queries — no JOINs, no
→ TTL built in — auto-expire keys WHERE with multiple conditions
[Link] 13/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
Storing 1TB of data in Redis requires ~1TB of RAM. At cloud prices, that's ~$10,000/month.
The same data on disk (SSD) costs ~$100/month. This is why Redis is typically used as a
caching layer (store only hot data in Redis, rest on disk) rather than a primary database for
large datasets. Use Redis for the hottest 5-10% of your data.
[Link] 14/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
Twitter/X Timeline caching, 800M+ timelines cached. Sub-ms reads. Without Redis,
session store every page load would query the DB for 300+ tweets.
Instagram Like counters, feeds, Atomic INCR for like counts. Sorted sets for feed ranking.
suggestions 300M+ DAU need instant response.
GitHub Job queue, caching, Background job queue (Resque/Sidekiq uses Redis).
real-time features Cache for repo metadata. Real-time notifications.
Snapchat Rate limiting, real-time Rate limit API calls per user. Fast pub/sub for chat
messaging messages. Ephemeral data (TTL = natural fit).
Pinterest Session store, follower Sets for "who follows whom." Sorted sets for feed ranking.
lists, feeds Session data shared across servers.
Airbnb Search result caching, Cache expensive search queries. Session store across
sessions microservices. Feature flags.
Slack Real-time presence, "Online" status indicators. Pub/sub for message delivery.
message broker Rate limiting for API.
Stack Caching (primary speed Entire site rendered from Redis cache. 50M+ page
Overflow layer) views/day served at sub-ms latency.
Every major tech company uses Redis — but almost never as the only database. Redis sits in
front of a primary database (PostgreSQL, MongoDB, Cassandra) as a speed layer. It caches
hot data, handles counters, manages sessions, and powers real-time features. The primary
[Link] 15/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
database handles durability and complex queries. This combination is the standard
architecture for any application serving more than a few thousand users.
Three reasons: (1) All data is in RAM — RAM access is ~100,000x faster than disk. (2) Single-
threaded event loop — no locks, no context switching, no concurrency overhead. Every
operation is atomic by default. (3) Simple data structures with O(1) or O(log N) operations —
GET is O(1), sorted set operations are O(log N). The bottleneck is network I/O, not the database
itself.
Because each operation takes about 1 microsecond (it's just a RAM lookup). In one second,
there are 1,000,000 microseconds. Even with network overhead, a single Redis instance
handles 100,000-300,000 operations per second. For more throughput, you use Redis
Cluster to shard across multiple instances — each instance handles its share of requests in
parallel.
Q3: "HOW DO YOU HANDLE THE RISK OF DATA LOSS WITH REDIS?"
Use both persistence mechanisms: RDB snapshots for periodic backups + AOF (append-only
file) with appendfsync everysec for near-real-time durability. Additionally, use replication —
even if the master crashes, a replica has the data. For critical data that must never be lost, use
Redis as a cache only — the source of truth stays in PostgreSQL/MySQL, and Redis can be
rebuilt from the primary database.
Sliding window counter: For each user, create a key like rate:user:1001:minute . On each
request: INCR the counter (atomic!). If it's the first increment, EXPIRE the key in 60 seconds.
If the counter exceeds the limit (e.g., 100), reject the request. After 60 seconds, the key auto-
expires and the counter resets. This is O(1) per request and handles millions of users with
minimal memory.
[Link] 16/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
Use SET lock:resource NX EX 30 . NX means "set only if not exists" (atomic check-and-set).
EX 30 means auto-expire in 30 seconds (prevents deadlocks if the holder crashes). To release:
DEL lock:resource (only if we hold it — use Lua script for atomic check-and-delete). For
stronger guarantees across multiple Redis instances, use the Redlock algorithm (acquire locks
on majority of N independent instances).
Redis: richer data structures (sorted sets, lists, streams), persistence (RDB/AOF), replication,
pub/sub, Lua scripting, cluster mode. Choose Redis for leaderboards, queues, sessions,
complex caching.
Memcached: simpler (strings only), multi-threaded (can use all CPU cores natively), slightly
faster for pure string caching at very high throughput. Choose Memcached for simple
string/object caching where you don't need data structures.
In practice: Redis has largely replaced Memcached because it does everything Memcached
does plus much more.
8 DATA STRUCTURES
Strings (cache, counters, locks). Hashes (user sessions, profiles). Lists (queues, feeds). Sets
(unique items, mutual friends via SINTER). Sorted Sets (leaderboards, ranking). Bitmaps (DAU
tracking, 12MB for 100M users). HyperLogLog (unique counts, 12KB for 1B items). Streams
(event log like Kafka).
PERSISTENCE
RDB: periodic snapshots, compact, fast restart, may lose data since last snapshot. AOF: log
every command, minimal loss (1 sec), larger file, slower restart. Production: use BOTH.
CACHING PATTERNS
Cache-Aside (most common): check Redis → miss → query DB → store in Redis + TTL. Write-
Through: write to Redis + DB simultaneously. Write-Behind: write Redis only, async flush to DB.
[Link] 17/18
04/04/2026, 13:40 Redis — Complete Deep Dive from Zero to Expert
EVICTION POLICIES
allkeys-lru (most common) = remove least recently used. allkeys-lfu = least frequently used.
volatile-ttl = closest to expiring. noeviction = return error.
SCALING
Replication: master + read replicas (async). Sentinel: auto-failover watchdog. Cluster: data
sharded across masters using 16,384 hash slots. CRC16(key) % 16384 → slot → node.
BEYOND CACHING
Sessions, rate limiting (INCR+TTL), distributed locks (SETNX+EX), leaderboards (ZADD),
pub/sub, geospatial (GEORADIUS), message queues (BLPOP), analytics (bitmaps/HLL), feature
flags.
TRADE-OFFS
Strengths: fastest possible reads/writes, rich data structures, atomic ops, TTL, pub/sub, Lua
scripting, cluster mode.
Weaknesses: RAM is expensive (data must fit in memory), no complex queries/JOINs,
persistence is best-effort, single-threaded can block on heavy Lua, cross-slot operations fail in
cluster.
WHEN TO USE
Use: caching (always), sessions, leaderboards, rate limiting, locks, counters, real-time features,
geospatial, temp data. Don't use: data > RAM, complex queries, guaranteed durability, relational
data, large blobs.
COMPANIES
Twitter (timeline cache), Instagram (like counters), GitHub (job queues), Snapchat (rate limiting),
Pinterest (feeds), Uber (geospatial), Slack (presence), Stack Overflow (entire site cache).
REDIS VS MEMCACHED
Redis: data structures + persistence + replication + pub/sub. Memcached: simpler, multi-
threaded, slightly faster for pure string cache. Redis has largely replaced Memcached.
[Link] 18/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
N O S Q L D E E P D I V E — T I M E - S E R I E S DATA B A S E
DEFINITION
Time-series data is a sequence of data points indexed by time. Each data point represents a
measurement or event that occurred at a specific moment. The data arrives in chronological
order, is append-only (you almost never update old readings), and is often queried by time
ranges ("give me the last 5 minutes" or "compare today vs yesterday").
Imagine a thermometer that records the temperature every second. At 9:00:01 it reads 28°C, at
9:00:02 it reads 28.1°C, at 9:00:03 it reads 28.2°C. After a year, you have 31 million readings
— all timestamped. You never go back and "edit" what the temperature was at 9:00:01. You
only add new readings. And your questions are always time-based: "What was the average
temperature last hour?" or "When did it exceed 40°C?" That's time-series data — and it's
fundamentally different from the data in a user profile or a shopping cart.
SERVER MONITORING:
timestamp │ host │ cpu_usage │ memory_used │ disk_io
2024-03-15T09:00:01Z │ web-01 │ 45.2% │ 8.1 GB │ 120 MB/s
2024-03-15T09:00:02Z │ web-01 │ 47.8% │ 8.2 GB │ 118 MB/s
2024-03-15T09:00:01Z │ web-02 │ 32.1% │ 6.5 GB │ 95 MB/s
...millions per day...
IOT SENSORS:
timestamp │ sensor_id │ temperature │ humidity │ pressure
2024-03-15T09:00:00Z │ factory-1 │ 28.5°C │ 65% │ 1013 hPa
[Link] 1/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
FINANCIAL DATA:
timestamp │ symbol │ price │ volume
2024-03-15T09:30:00Z │ AAPL │ 172.50 │ 1,234,567
2024-03-15T09:30:01Z │ AAPL │ 172.52 │ 987,654
APPLICATION METRICS:
timestamp │ endpoint │ response_time │ status_code
2024-03-15T09:00:00Z │ /api/users │ 45ms │ 200
2024-03-15T09:00:00Z │ /api/products │ 120ms │ 200
[Link] 2/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
2 What Is InfluxDB?
DEFINITION
InfluxDB uses unique terminology that confuses beginners. Understanding these terms is
essential before writing any queries.
[Link] 3/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
│ │ │ └─ Timestamp
│ │ │ (nanoseconds since epo
│ │ └─ FIELDS (the values)
│ │ NOT indexed. For actual measurements.
│ TAGS (metadata)
└─
│ INDEXED! For filtering and grouping.
│ host, region, sensor_id, etc.
└─ MEASUREMENT NAME
Like a table name.
WHAT IS A "SERIES"?
A series = unique combination of measurement + tag set
cpu + {host=web-01, region=us-east} = ONE series
100 hosts × 3 regions = 300 series. Each series is stored contiguously on disk.
[Link] 4/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
InfluxDB uses the TSM (Time-Structured Merge Tree) engine — a custom storage engine
inspired by LSM Trees (like Cassandra) but optimised specifically for time-series data. It
achieves massive write throughput with excellent compression because timestamps are
sequential and highly compressible.
Step 4: COMPACTION
[Link] 5/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
READ PATH:
1. Check in-memory cache (recent data — instant)
2. Check TSM files on disk (use index to jump to right file + offset)
3. TSM files are organised by SERIES — all data for one series
is stored contiguously → sequential reads = fast
4. Time range queries: binary search to start offset, scan forward
→ O(log N) seek + O(K) scan where K = result size
At 1 data point per second per sensor, you generate 86,400 points per day per sensor. With
10,000 sensors, that's 864 million points per day. After a year: 315 billion points. You can't
keep all of this at full resolution forever. But you still need historical trends. The solution:
retention policies + downsampling.
RETENTION POLICY:
"Keep data for X duration, then automatically delete it."
[Link] 6/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
DOWNSAMPLING:
"Aggregate high-resolution data into lower-resolution summaries."
Downsampled to per-minute:
09:00 → cpu_avg=45.6, cpu_max=47.8, cpu_min=43.1
Downsampled to per-hour:
09:00 → cpu_avg=44.2, cpu_max=62.3, cpu_min=28.7
[Link] 7/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
InfluxDB has two query languages: InfluxQL (SQL-like, older) and Flux (functional, newer, more
powerful). InfluxDB 2.x+ uses Flux as the primary language.
// HTTP API:
POST /api/v2/write?bucket=server_metrics
Content-Type: text/plain
[Link] 8/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
from(bucket: "raw_metrics")
[Link] 9/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
-- Filter by tag
SELECT usage FROM cpu WHERE host = 'web-01' AND time > now() - 1h
6 Scaling InfluxDB
[Link] 10/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
SCALING STRATEGIES:
1. Vertical: more RAM, faster SSDs, more CPU cores
2. Functional sharding: different metrics on different instances
(server metrics on Instance 1, IoT data on Instance 2)
3. Time-based sharding: recent data on fast SSD, old data on HDD
4. InfluxDB Cloud/Enterprise for true horizontal scaling
InfluxDB is often used as part of the TICK stack — a complete open-source monitoring
platform. Each letter represents a component: Telegraf (data collection), InfluxDB (storage),
Chronograf (visualization), Kapacitor (alerting). In modern setups, Grafana often replaces
Chronograf for dashboards.
[Link] 11/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
DATA SOURCES
Grafana
Servers (CPU/RAM)
Containers (Docker) T I Dashboards
Visualization DevOps /
Databases (PG/MySQL) Telegraf InfluxDB SRE Team
IoT Sensors Data Collector Time-Series Store
Views dashboards
APIs, Apps, Networks 200+ input plugins TSM Engine K Gets alerts
Retention + Downsample
Cloud Services Kapacitor
Alerts (Slack, PD)
8 Read-Heavy vs Write-Heavy
[Link] 12/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
If you make a high-cardinality value a tag (like user_id with millions of distinct values),
InfluxDB creates a separate series for every unique tag combination. 1M users × 10 metrics =
10M series. The in-memory index must track all series → RAM explodes, queries slow down.
Rule: tags should have low cardinality (host, region, datacenter — tens to hundreds of values).
High cardinality values should be fields (not indexed, but stored efficiently).
[Link] 13/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
Tesla Vehicle sensor data from IoT time-series at massive scale. Per-second readings from
millions of cars thousands of sensors per vehicle. Auto-expiry for old data.
IBM Infrastructure monitoring Millions of servers, each emitting dozens of metrics. Need
across global cloud time-range queries for dashboards and alerting.
Hulu Streaming quality metrics Buffer rates, video quality per stream. Millions of
concurrent streams = millions of data points/sec.
Robinhood Financial market data Stock price ticks. Nanosecond timestamp precision. Time-
range queries for charts.
Every company using InfluxDB has the same data pattern: continuous streams of
timestamped measurements arriving at high speed, queried by time ranges, and needing
[Link] 14/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
automatic lifecycle management. None of them use InfluxDB for user accounts, shopping
carts, or relational data — it's purely for metrics, monitoring, and time-series analytics.
QUERY
DATABASE ARCHITECTURE BEST FOR LIMITATION
LANGUAGE
InfluxDB: standalone TSDB, IoT, general monitoring, great ecosystem (Telegraf + Grafana).
Prometheus: Kubernetes-native, pull-based, short-term storage (pair with Thanos for long-
term).
TimescaleDB: when you need TSDB + SQL JOINs + relational data in one database.
ClickHouse: when you need heavy SQL analytics on billions of time-series rows.
[Link] 15/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
Q1: "WHY CAN'T YOU JUST USE POSTGRESQL FOR TIME-SERIES DATA?"
You can — but it's 10-100x less efficient. PostgreSQL isn't optimised for the unique
characteristics of time-series: (1) Write speed — InfluxDB's TSM engine handles millions of
inserts/sec; PostgreSQL struggles past hundreds of thousands. (2) Compression — InfluxDB
uses time-aware encoding (delta-of-delta for timestamps, XOR for floats) achieving 90-95%
compression; PostgreSQL stores raw values. (3) Retention — InfluxDB auto-deletes expired
data; PostgreSQL needs manual DELETE (slow, locks table). (4) Downsampling — InfluxDB has
built-in tasks; PostgreSQL needs custom cron jobs. For small-scale time-series, PostgreSQL
works. At scale, a purpose-built TSDB is necessary.
InfluxDB creates a separate series for every unique combination of measurement + tags. If
you use a high-cardinality value as a tag (like user_id with millions of values), the number of
series explodes. The in-memory index must track every series, consuming RAM and slowing
queries. Solution: only use low-cardinality metadata (host, region, sensor_type) as tags. High-
cardinality identifiers should be fields (not indexed). InfluxDB 3.0 (IOx) is redesigned to handle
unlimited cardinality.
Tags are indexed metadata used for filtering and grouping — like WHERE host='web-01'. They
should have low cardinality (few distinct values). Fields are the actual measured values
(cpu=45.2%) — NOT indexed. They can have high cardinality (infinite distinct values). Making
a high-cardinality value a tag is the number one performance mistake in InfluxDB.
for non-Kubernetes environments. Choose Prometheus for Kubernetes; InfluxDB for everything
else.
DATA MODEL
Bucket (database) → Measurement (table) → Points (rows). Each point: timestamp + tags
(indexed metadata, low cardinality) + fields (values, NOT indexed). Series = measurement +
unique tag set. High cardinality tags = #1 performance killer!
TSM ENGINE
WAL (append-only, durability) + In-memory Cache (serves recent queries, fast ACK) → TSM
Files (immutable, compressed, sorted by series+time) → Compaction (merge, cleanup). Like
Cassandra's LSM but optimised for timestamps.
COMPRESSION
Timestamps: delta-of-delta encoding (sequential → tiny). Floats: XOR encoding (Facebook
Gorilla). Result: 1TB raw → ~50-100GB on disk.
QUERIES
Flux: from(bucket) |> range(start: -1h) |> filter() |> aggregateWindow(every: 5m, fn:
mean) . InfluxQL: SQL-like syntax. Time-range queries, aggregations, derivatives, downsampling
tasks.
TICK STACK
Telegraf (collect) → InfluxDB (store) → Grafana/Chronograf (visualize) → Kapacitor (alert).
Standard monitoring architecture.
SCALING
[Link] 17/18
04/04/2026, 13:41 InfluxDB — Complete Deep Dive from Zero to Expert
OSS = single node. Cloud = managed, auto-scaling. Enterprise = clustered, HA. 3.0 (IOx) =
Apache Arrow + Parquet, unlimited cardinality, object storage.
WHEN TO USE
Use: server monitoring, IoT sensors, APM, financial ticks, DevOps metrics, network monitoring.
Don't use: user data, CRUD apps, JOINs, full-text search, caching, high-cardinality tags.
COMPANIES
Tesla (vehicle sensors), IBM (infra monitoring), Cisco (network), eBay (APM), PayPal
(transactions), Hulu (streaming quality), Robinhood (market data).
VS ALTERNATIVES
Prometheus: Kubernetes-native, pull-based, short-term. TimescaleDB: TSDB + SQL on
PostgreSQL. ClickHouse: columnar, heavy analytics. InfluxDB = best general-purpose
standalone TSDB.
[Link] 18/18