Chapter 25: Key-Value and Document Stores
Key-Value Stores: Redis
The simplest data model: a key maps to a value. Like a hash map that persists.
# Redis commands
SET user:123 '{"name":"Alice","email":"alice@ex.com"}'
GET user:123
DEL user:123
EXPIRE user:123 3600 # auto-delete after 1 hour (TTL)
INCR page_views:home # atomic increment
# Data structures beyond simple strings:
HSET user:123 name "Alice" age 30 # hash (like a mini-row)
LPUSH queue:jobs "job1" "job2" # list (queue)
SADD tags:post:1 "grpc" "db" # set
ZADD leaderboard 100 "alice" # sorted set (score-based)
Redis Use Cases
- Caching: cache DB query results, reduce load on PostgreSQL
- Sessions: store user sessions with TTL
- Rate limiting: INCR + EXPIRE for request counting
- Job queues: LPUSH/BRPOP for producer/consumer
- Real-time leaderboards: sorted sets
- Pub/Sub: real-time messaging
⚠️ Redis Limitations
- Data must fit in RAM (it's an in-memory database)
- No complex queries (no WHERE, no JOIN)
- Persistence is optional and has trade-offs (RDB snapshots vs AOF log)
- Single-threaded for commands (but very fast due to no disk I/O)
Document Stores: MongoDB
Stores JSON-like documents (BSON). Each document can have different fields.
// MongoDB document
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
addresses: [
{ type: "home", city: "Stockholm" },
{ type: "work", city: "Gothenburg" }
],
preferences: { theme: "dark" }
});
// Query
db.users.find({ "addresses.city": "Stockholm" });
// Aggregation pipeline
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customer_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
]);
When Document Stores Shine
- Content management (articles, products with varying attributes)
- User profiles with flexible fields
- Event logging
- Rapid prototyping (no schema migrations)
When They Don't
- Data with many relationships (use relational)
- Need for JOINs across collections
- Strong consistency requirements
Key Takeaways
- Redis: in-memory KV store for caching, sessions, queues. Sub-millisecond.
- MongoDB: flexible-schema document store. Good for varying structures.
- Both sacrifice query flexibility for specific access pattern performance
- Often used alongside PostgreSQL, not instead of it