lesson

Databases & Caching

SQL vs NoSQL, indexing, replication, Redis caching patterns.

Databases & Caching

SQL vs NoSQL — When to Use Each

SQL (Postgres, MySQL)NoSQL (MongoDB, DynamoDB)
SchemaFixed, relationalFlexible, document/key-value
ConsistencyStrong (ACID)Eventually consistent (tunable)
JoinsNativeManual (application-level)
ScalingVertical (read replicas help)Horizontal (sharding built-in)
Best forComplex queries, transactions, reportingHigh throughput, flexible schema, key-value access
Rule of thumb: start with SQL. Move to NoSQL only when you hit a specific limitation.


Caching with Redis

Cache-Aside Pattern (most common)

1. Check cache → hit? Return cached value.
  • Miss? Query database, store result in cache, return.
  • On write: invalidate cache key.
  • Cache-Through Pattern

    Application → Cache → Database (cache handles all reads/writes)

    Key Decisions

  • TTL (time-to-live): how long before cached data expires?
  • Invalidation: when data changes, how do you update the cache?
  • Thundering herd: what happens when cache expires and 1000 requests hit the DB simultaneously?
  • Solutions: cache warming, request coalescing (single-flight), stale-while-revalidate.


    Indexing

  • B-Tree (default): equality, range, ORDER BY
  • Hash: equality only (fast)
  • GIN: arrays, JSONB, full-text search
  • Composite index: index on (a, b) — useful for multi-column WHERE clauses
  • Golden rule: index columns that appear in WHERE, JOIN, ORDER BY. Don't over-index (slows writes).

    Sign in to use the AI study buddy on this lesson.

    Resources