C
Database/NoSQL/Lesson 05

NoSQL Basics — When to Use Redis and MongoDB

45 min·theory

NoSQL Basics — When to Use Redis and MongoDB

🎯 What you will be able to do after this lesson

After completing this lesson, you will be able to confidently do the following three things.

  • ✅ Apply RDBMS vs NoSQL selection criteria (consistency vs flexibility)
  • ✅ Apply the three core Redis use cases (cache · session · rate limit)
  • ✅ Identify when MongoDB documents are the right fit — and when they are not

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

Why NoSQL Emerged

The Strength of RDBMS — Data Integrity

MySQL and PostgreSQL are industry standards validated over decades. They guarantee data consistency through transactions, foreign keys, and normalization.

The Limitation of RDBMS — Difficult to Scale Horizontally

  • When traffic surges, a single server hits its ceiling
  • Splitting data across multiple servers (sharding) is hard — JOINs and foreign keys break across server boundaries
  • Every row has the same column structure — limited flexibility

The Four Types of NoSQL

TypeRepresentativeData ModelWhen to Use
Key-ValueRedis, DynamoDBkey → valuecache · session
DocumentMongoDB, CouchbaseJSON documentflexible schema, rapid development
Wide-ColumnCassandra, HBasecolumn familyhigh-volume time-series
GraphNeo4jnode + relationshipSNS, recommendations

Practical Selection Criteria — RDBMS as the Default

As of 2026, most new projects still use RDBMS as the primary store. NoSQL is used as a supplement for specific purposes:

code
[Web App]
   ↓
[MySQL] ← users · orders · products (consistency matters)
[Redis] ← cache · session · ranking (speed matters)
[Elasticsearch] ← full-text search (optional)

"MySQL + Redis" is the 80% standard combination in production. The trend of starting a project with MongoDB as the primary database is gradually declining.

Redis — Three Patterns: Cache · Session · Rate Limit

Why Redis Is Fast

All data is kept in memory. If MySQL operates at disk speed (milliseconds), Redis operates at memory speed (microseconds) — a 100x difference.

Pattern 1 — Cache (the most common use case)

python
def get_user(user_id):
    cached = redis.get(f"user:{user_id}")
    if cached:
        return json.loads(cached)        # cache hit → no DB call

    user = db.query("SELECT * FROM users WHERE id = ?", user_id)
    redis.setex(f"user:{user_id}", 300, json.dumps(user))   # cache for 5 min
    return user

Extremely effective when reads vastly outnumber writes (e.g., 100 reads for every 1 write).

Cache Invalidation — The Hardest Problem

python
def update_user(user_id, data):
    db.update(...)
    redis.delete(f"user:{user_id}")   # invalidate cache immediately

"There are only two hard things in Computer Science: cache invalidation and naming things." — Missed cache invalidation is a classic source of production bugs.

Pattern 2 — Session Store

python
# Save session on login
session_id = secrets.token_urlsafe(32)
redis.setex(f"session:{session_id}", 86400, user_id)   # valid for 24 hours

# Validate on each request
user_id = redis.get(f"session:{session_id}")
if not user_id:
    raise Unauthorized()

Multiple servers (e.g., a Tomcat cluster) can share the same session. Unlike JWT, the session can be invalidated instantly on the server side.

Pattern 3 — Rate Limit

python
def check_rate_limit(user_id, limit=100, window=60):
    key = f"rate:{user_id}"
    count = redis.incr(key)
    if count == 1:
        redis.expire(key, window)        # set TTL on first request
    if count > limit:
        raise TooManyRequests()

Blocks requests exceeding 100 per minute. Implemented in just two lines: INCR + EXPIRE. Serves as API abuse prevention and a first line of DDoS defense.

Other Common Use Cases

  • RankingZADD leaderboard 100 user1real-time leaderboard with Sorted Sets
  • Pub/Sub — lightweight message broker (suitable for small scale)
  • Distributed Lock — Redlock algorithm (use with caution)

Limitation — Weak on Persistence

If memory is lost, so is the data. AOF and RDB backups exist, but Redis is not suitable as a primary data store. Always follow the pattern of source of truth in the DB, cache in Redis.

MongoDB — Document Structure and When to Use It

What Is a Document?

A single record is a JSON-like document. No need to define columns upfront.

json
// users collection (= RDBMS table)
{
    "_id": ObjectId("..."),
    "email": "[email protected]",
    "name": "Alice",
    "address": {
        "city": "Seoul",
        "zip": "06000"
    },
    "hobbies": ["coding", "music"]
}

Objects and arrays are stored as-is. A structure that would require 3 tables + JOINs in RDBMS fits into a single document.

Basic Queries

javascript
// Insert
db.users.insertOne({ email: "[email protected]", name: "Alice", age: 30 });

// Find
db.users.find({ age: { $gte: 18 } });

// Update
db.users.updateOne(
    { email: "[email protected]" },
    { $set: { age: 31 } }
);

// Delete
db.users.deleteOne({ email: "[email protected]" });

When MongoDB Is the Right Fit

✅ Good Fit

  • Flexible schema — content metadata (videos, articles — fields vary per entry)
  • Rapid prototyping — lower migration overhead
  • Log / event storage — time-series data
  • Hierarchical data — comment trees, navigation menus

❌ Poor Fit

  • Transactions + strong consistency — MongoDB supports transactions, but they are not as robust as RDBMS
  • Complex JOINs — MongoDB's $lookup is slow
  • Fixed schema + data integrity — users, payments, orders — MySQL is the right answer

One-Line Comparison with RDBMS

MySQLMongoDB
Data Modeltable + columncollection + document
Schemafixed (DDL required)flexible (on the fly)
JOINpowerfullimited ($lookup)
transactionstrong (ACID)supported from 4.0+ (with caveats)
Scalingvertical scaling preferredhorizontal scaling (sharding) easier
Learning Curvestandard SQLproprietary query language

Recommended Learning Order

1. Master MySQL first — the shared foundation for all backend developers
2. Redis — cache and session are the most frequently needed
3. MongoDB — tackle it when a project actually calls for it

Saying "I know MySQL well" is far more powerful in interviews than "I know NoSQL."

🤖 Try Prompting AI Like This

Once you understand the concepts in this lesson, you can give AI specific, precise instructions. Instead of a vague "fix this," you can make requests using the right vocabulary — and that is exactly where token savings begin.

  • "Design 3 tables — users, orders, and products — including foreign keys and indexes"
  • "Write a query that aggregates the number of new signups per day for the past 7 days"
  • "Prepend EXPLAIN to this query and interpret the execution plan for me"

Why This Reduces Tokens

Without the underlying concepts, you still have to ask "What does that mean?" after reading an AI response. Those follow-up questions are what eat up your tokens. Learn the concept once, and the conversation wraps up in a single exchange.

NoSQL Basics — When to Use Redis and MongoDB - Database