Reading Mode
CH 14·Lesson 6
Phase 6 — Redis & PostgreSQL — Checkpoint Answer Guide
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
advanced8 min read
Learning Objectives
- Redis Basics & Patterns
- Redis Advanced
- PostgreSQL Mastery
- CAPSTONE: High-Performance Analytics API
- Professional standard
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
Redis Basics & Patterns
- Data structures: Redis data types expose server-side operations whose complexity and atomicity are more important than their superficial shape. A strong answer also explains that the server selects compact encodings for small values and changes representation as data grows. One command executes atomically relative to other commands. The main warning is: Large aggregate keys create latency spikes, replication cost, and difficult resharding.
- Caching strategies: A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. A strong answer also explains that cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses. The main warning is: Delete/update races can repopulate stale values; cache correctness is a protocol.
- Distributed locking: A distributed lock is a time-bounded lease granting temporary coordination, while a fencing token lets the protected resource reject stale owners. A strong answer also explains that redis
SET key token NX PX ttlacquires one lease and a compare-delete script releases only the owner's token. Redlock combines independent nodes under timing assumptions. The main warning is: A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. - Pub/Sub & Redis GEO: Pub/Sub delivers live messages to currently connected subscribers; GEO indexes locations in a sorted set representation for radius or box search. A strong answer also explains that pub/Sub does not retain history. GEO commands encode coordinates to sortable scores and filter candidates by geometry. The main warning is: Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine.
- Expiry, eviction & transactions: A caching strategy defines who populates, invalidates, and recovers a cache and whether stale reads are acceptable. A strong answer also explains that cache-aside reads the database on miss; write-through updates both synchronously; write-behind queues persistence. Expiry bounds staleness but can synchronize misses. The main warning is: Delete/update races can repopulate stale values; cache correctness is a protocol.
Redis Advanced
- Redis Cluster & Sentinel: Cluster shards keys across 16,384 hash slots; Sentinel monitors a primary-replica deployment and coordinates failover without sharding. A strong answer also explains that clients follow MOVED/ASK redirects in Cluster. Sentinel quorum detects failure and a majority authorization elects a new primary. The main warning is: Asynchronous replication can lose acknowledged writes during failover.
- Redis Streams: Redis Streams are retained, ordered entry logs whose consumer groups track delivery and pending ownership independently for each group. A strong answer also explains that
XREADGROUPassigns entries, the pending entries list records unacknowledged work,XACKcompletes it, andXAUTOCLAIMtransfers sufficiently idle work after a consumer failure. The main warning is: Redis Stream consumer groups are not Kafka partition groups: several consumers can own different entry IDs without persistent partition ownership. - Lua scripting: Redis Lua executes a multi-command decision atomically on the server. A strong answer also explains that the script blocks other command execution until it finishes; EVALSHA reuses a cached script body and clients recover from NOSCRIPT. The main warning is: Long loops block Redis, and Cluster scripts can access only colocated keys.
- Operations & testing: Redis operational work proves failover, resharding, memory policy, client redirection, and recovery behavior against a real server topology. A strong answer also explains that cluster resharding migrates hash slots while clients follow MOVED or ASK responses; Sentinel promotes a replica after quorum and majority authorization; persistence and replication influence acknowledged-write recovery. The main warning is: The word migration here means moving Redis slots or topology state, not a Django schema migration.
PostgreSQL Mastery
- Advanced SQL: A window function calculates across a related row set without collapsing each input row as GROUP BY does. A strong answer also explains that the executor partitions and orders rows, then applies a frame. Ranking ignores frame bounds, while aggregates and FIRST/LAST behavior can depend on them. The main warning is: Default RANGE frames can include peers and surprise LAST_VALUE or cumulative totals.
- PostgreSQL internals: MVCC gives transactions snapshots of tuple versions; WAL records changes for crash recovery and replication; vacuum reclaims versions no active snapshot needs. A strong answer also explains that each plan node exposes estimated and actual rows, loops, time, buffers, and sometimes disk spill. pg_stat_statements aggregates normalized query statistics. The main warning is: A long transaction prevents cleanup, and EXPLAIN ANALYZE executes the statement.
- Index types & optimization: An index is an auxiliary access path optimized for particular operators, ordering, and data distribution. A strong answer also explains that b-tree handles equality/range/order; GIN maps values or tokens to rows; GiST supports extensible geometric strategies; BRIN summarizes physical page ranges. Index-only scans still depend on visibility metadata. The main warning is: Every index adds write, vacuum, storage, and cache cost; column order and predicate matching matter.
- Partitioning & pgvector: Partitioning divides one logical table into physical children; vector indexes approximate nearest neighbors; hybrid search combines semantic and lexical evidence. A strong answer also explains that the planner prunes partitions from compatible predicates. HNSW builds a navigable graph; IVFFlat probes selected clusters. Full-text search uses lexemes and ranking. The main warning is: Too many partitions raise planning cost; approximate indexes trade recall for speed.
- Transactions & concurrency: Transaction isolation determines which concurrent histories are visible; locks and serializable conflict detection protect invariants that a snapshot alone cannot. A strong answer also explains that read Committed takes a new snapshot per statement; Repeatable Read holds a transaction snapshot; PostgreSQL Serializable adds predicate-conflict tracking and can abort a dangerous structure. SKIP LOCKED lets workers claim different rows, and HOT can update an unindexed tuple within its page. The main warning is: SKIP LOCKED is suitable for queues, not ordinary user reads; retrying the whole transaction is mandatory after serialization failure.
- SQLAlchemy integration: SQLAlchemy integration maps explicit engine, connection, session, transaction, statement, and streaming-result lifecycles onto PostgreSQL behavior. A strong answer also explains that an engine owns a bounded pool; a session owns identity-map and unit-of-work state; a transaction pins a connection; server-side cursors or
yield_peravoid materializing an unbounded result at once. The main warning is: An ORM session is not an authentication scope, and streaming rows is not an LLM streaming response.
CAPSTONE: High-Performance Analytics API
- Schema design: Monthly range partitioning stores orders in child tables selected by an order timestamp while preserving one logical parent relation. A strong answer also explains that postgreSQL routes inserts by partition bounds and prunes children when query predicates constrain the partition key. Unique constraints across partitions generally must include that key, and each child owns local indexes. The main warning is: Missing partitions reject inserts, and queries without partition-key predicates may scan every child and increase planning cost.
- Endpoints with targets: The dashboard endpoint has two explicit latency paths: a versioned Redis result under 50 ms and a bounded authoritative fallback under 500 ms. A strong answer also explains that the handler authenticates and scopes the cache key, reads a serialized projection, and on miss queries the materialized report or optimized SQL. It writes with TTL jitter and protects concurrent misses before returning freshness metadata. The main warning is: A cache key missing tenant/filter/version data can leak or mislabel results, while an unbounded miss path creates a stampede exactly during cache loss.
- Infrastructure: Cluster shards keys across 16,384 hash slots; Sentinel monitors a primary-replica deployment and coordinates failover without sharding. A strong answer also explains that clients follow MOVED/ASK redirects in Cluster. Sentinel quorum detects failure and a majority authorization elects a new primary. The main warning is: Asynchronous replication can lose acknowledged writes during failover.
Professional standard
A complete response identifies the boundary, guarantee, state owner, lifecycle, failure, and proof. Award less credit to answers that name tools without explaining why their guarantees fit the requirement.
Mastery check
How well can you recall this?
Finished this lesson?