Replicas, Caching & Retention in SQL
Lag tolerance decides what leaves the primary
Overloaded primaries shed lag-tolerant reads to replicas (dashboards yes, balances no), pre-aggregate (rollups, matviews, result caches with invalidation), shape queries (narrow columns, keyset pagination). Writes stay primary; replica lag bounds placement. Retention: time-partition + DROP PARTITION (instant, no bloat) beats giant DELETE; batched deletes with pauses are the fallback.
Move lag-tolerant reads
Dashboards, reports → replicas. Balances, writes → primary.
Cache + precompute
Result caches with invalidation; rollups/matviews for hot shapes.
Shape the query
Narrow columns, keyset pagination, indexed paths — less per read.
Retain by partition
RANGE-partition by time; DROP old partitions instant. Batched DELETE fallback.
1-- batched retention fallback (repeat, advancing):2DELETE FROM events WHERE created_at < '2023-01-01' LIMIT 10000;
| strategy | verdict |
|---|---|
| partition-drop | instant, no bloat — gold |
| batched-delete | replica-friendly fallback |
Dropping a 2022 partition deallocates pages with one catalog change. Batched deletes keep each txn small with pauses so replicas stay close — single giant DELETE would lock, bloat and lag.
What moves where
Lag tolerance is the router.
1-- primary: balances, writes, read-your-write2-- replica: dashboards, rollups, exports (lag OK)
| node | work |
|---|---|
| primary | writes + fresh |
| replica | lag-tolerant scans |
Retention without downtime
Partition-drop gold, batched fallback.
1ALTER TABLE events DROP PARTITION FOR ('2022-01-01');2-- fallback:3DELETE FROM events WHERE created_at < '2023-01-01' LIMIT 10000;
| strategy | verdict |
|---|---|
| drop partition | instant, no bloat |
| batched delete | pauses, replica-kind |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.