Considering data management strategies
I need to think about using read replicas for analytics queries and the risk of heavy queries causing replication lag, which could affect failover. It might be wise to use a dedicated analytics replica separate from the high availability (HA) replica. Additionally, introducing "streams" for event streaming could ensure incremental updates, but could complicate joins. I’ll organize my final response into sections covering requirements, data movement patterns, reference architecture, and more, making sure it remains concise.
1) Target: “HTAP‑lite” bridge goals
You’re not building a single HTAP database; you’re building a low-latency analytics path that:
- Does not harm OLTP (latency, lock contention, I/O).
- Provides bounded freshness (e.g., seconds–minutes).
- Gives clear semantics (“what data is included?”) and operational safety (replay, backfill, schema change).
A good framing is: OLTP is the system of record; OLAP is a derived, eventually-consistent read model with explicit SLAs.
2) Change capture options (from simplest to most robust)
A) Pull from read replica (periodic ETL / incremental queries)
How: Stand up an OLTP read replica; run scheduled jobs that extract deltas (e.g., updated_at watermark), load into warehouse.
Pros
- Simple; few moving parts.
- Easy to reason about for small datasets.
Cons / gotchas
updated_at and “delta by timestamp” breaks with:
- late updates, clock skew, missed updates, deletes, out-of-order writes.
- Hard to get <5–10 min freshness reliably.
- High read load during extracts; can increase replica lag.
Use when
- Freshness SLA is 10–60 minutes+, data volume modest, correctness can be “best effort”.
B) Log-based CDC (preferred baseline for HTAP-lite)
How: Read the database’s replication log (Postgres WAL, MySQL binlog) and emit row-level changes into a durable stream (Kafka/Pulsar/Kinesis), then load/upsert into OLAP.
Typical tooling: Debezium (+ Kafka Connect), native logical replication, or cloud CDC services.
Pros
- Captures inserts/updates/deletes reliably.
- Near-real-time is achievable (seconds).
- Better correctness: ordered within a partition, includes transaction boundaries (depending on connector).
Cons / gotchas
- More infrastructure (connectors, topics, schema registry).
- Need idempotent sinks (duplicates can happen).
- Initial snapshot + catch-up requires careful orchestration.
Use when
- Freshness SLA seconds–a few minutes, correctness matters, you want replay/backfill.
C) Application events (domain events) / Outbox pattern (complements CDC)
How: Application writes business events (or an outbox table in the same OLTP transaction), a relay publishes to the stream.
Pros
- Events match business meaning (e.g., “OrderPlaced”), not row diffs.
- Avoids some impedance mismatch in analytics modeling.
Cons
- Risk of drift from source-of-truth tables unless rigorously governed.
- Still need replay strategy and schema evolution discipline.
Use when
- You need high-quality semantic events; often paired with CDC as safety net.
3) Read replicas vs streams: what they’re for (and how to combine them)
Read replicas are for…
- Offloading read-only transactional queries.
- Running batchy extracts when freshness is not extreme.
- Providing a safer place to run CDC readers (sometimes).
But: heavy analytics queries on a replica can still:
- Starve replication apply → replica lag → stale reads.
- Consume I/O/CPU needed for HA or failover readiness.
Recommendation
- If you use replicas, split roles:
- HA replica (protected; minimal extra load)
- CDC replica (dedicated to log decoding / snapshot)
- Ad-hoc read replica (for operational reporting; throttle users)
Streams are for…
- Continuous incremental propagation of change.
- Establishing a durable replayable log to feed multiple consumers (warehouse, caches, search, feature store).
- Achieving tight freshness SLAs with observability (“consumer lag”).
Common hybrid (practical HTAP-lite)
- Use log-based CDC to a stream.
- Use stream processors to build:
- Raw bronze tables (append-only or change-log)
- Curated silver/gold tables (upserted dimensions/facts, aggregates)
4) Reference architecture (practical, robust)
Source (OLTP)
- Postgres/MySQL primary (writes)
- Optional: dedicated CDC replica
Capture
- Debezium / logical replication / binlog reader
- Initial snapshot with a consistent point (LSN/binlog position)
- Emit to Kafka/Pulsar topics per table (or per domain)
Stream normalization
- Add metadata:
source_commit_ts, txid, lsn/binlog_pos, op (c/u/d)
- Enforce schema via registry
- Partitioning key: typically primary key for upsert topics; or order-id for fact streams
Serving storage (OLAP)
- Warehouse/lakehouse + OLAP engine:
- Snowflake/BigQuery/Redshift, or
- Iceberg/Delta + Trino/Spark, or
- ClickHouse/Druid for sub-second aggregates
Load strategy
- Write raw change-log (append) for audit/replay.
- Maintain query tables with:
- Upserts by PK + version/commit_ts (SCD1/SCD2)
- Partitioning by event date for facts
- Periodic compaction/merge
5) Freshness SLAs: define them explicitly (and make them measurable)
Measure “freshness” as an end-to-end lag
Define:
t_commit = time transaction commits in OLTP
t_visible = time the change is queryable in OLAP
- Freshness lag =
t_visible - t_commit
Track p50/p95/p99 and “max lag”.
Typical SLA tiers
- Near-real-time: p95 < 5–30s (harder; requires tuned CDC + streaming sinks)
- Operational analytics: p95 < 1–5 min (common HTAP-lite target)
- Business reporting: p95 < 15–60 min
What controls the SLA
Main contributors:
- CDC extraction latency (log read, connector throughput)
- Stream lag (broker health, partitioning, consumer backpressure)
- Transform latency (joins/aggregations/windowing)
- OLAP commit/merge latency (MERGE cost, compaction, small files)
Design for predictable freshness
- Prefer micro-batch or streaming upsert sinks designed for it.
- Avoid “MERGE per row” patterns in warehouses; batch merges by partition/time window.
- Use a watermark/high-water mark:
- Maintain a table
olap_ingestion_state with the latest fully applied source_commit_ts (or LSN).
- Queries can use
WHERE source_commit_ts <= watermark to guarantee completeness.
SLA monitoring (minimum set)
- Replication slot / binlog retention pressure (WAL growth)
- Connector lag (LSN vs flushed LSN)
- Broker consumer lag
- OLAP load job latency + failures
- End-to-end synthetic canary event (write a marker row, detect when visible)
6) Isolation: protecting OLTP and defining correctness
A) Performance isolation (don’t let OLAP hurt OLTP)
Rules of thumb:
- No analytical queries on OLTP primary.
- If using replicas, rate-limit extract jobs and protect HA replicas.
- Run CDC readers on a dedicated replica if decoding/snapshotting is heavy.
- Ensure OLTP has headroom for:
- WAL/binlog generation
- replication
- vacuum/compaction
Snapshot impact
- Initial snapshots can hammer OLTP. Mitigate via:
- off-peak snapshot
- chunked snapshotting by PK ranges
- snapshot from a replica
- throttling and connection pooling
B) Consistency/isolation semantics (what OLAP is allowed to see)
You need to choose (and document) a contract:
- Eventual consistency (default)
- OLAP may lag; within a table, updates might arrive out of order across partitions.
- Provide a watermark so users can request “complete up to time T”.
- Read-your-writes (per user/session)
- Hard across OLTP→OLAP. Usually achieved by:
- Routing those users to OLTP for just-written entities, or
- Hybrid query layer (fallback to OLTP for recent window), or
- Caching recent writes in a fast store merged at query time
- Transactional boundaries
- Some CDC tools can emit transaction metadata.
- If you require “all-or-nothing” visibility for multi-row transactions in OLAP, you need:
- Transaction markers + buffering until commit, or
- A sink that supports atomic batch commits per transaction group
- Many HTAP-lite systems accept transactional fuzziness and instead provide time-based completeness via watermark.
C) Idempotency + dedupe (critical for correctness)
Assume the pipeline is at-least-once unless proven otherwise.
Make sinks idempotent via one of:
- Upsert keyed by
(primary_key) with a version (e.g., source_commit_ts or LSN)
- Deduplicate by
(primary_key, source_lsn) in staging then compact
- For facts/events: immutable append + dedupe on
(event_id) if needed
D) Deletes
Plan explicitly:
- CDC produces delete records; in OLAP you can:
- apply hard deletes (costly in some warehouses), or
- use tombstones (
is_deleted=1, deleted_at) and filter in views, plus periodic purge
7) Recommended “default” HTAP-lite blueprint
If you want a generally solid design:
- CDC (log-based) → Kafka/Pulsar
- Store raw changelog (cheap append) + maintain curated query tables (upsert/merge)
- Define freshness SLA as end-to-end lag; publish a watermark
- Protect OLTP with:
- dedicated CDC replica (if needed)
- throttled snapshots
- strict ban on OLAP queries against primary
- Treat delivery as at-least-once; implement idempotent sinks
- Provide fall-back patterns for “just-written” data (query OLTP for last N minutes)
If you share: (1) your OLTP engine, (2) target OLAP store, (3) desired freshness (p95), and (4) whether you need transaction-level atomic visibility, I can propose a concrete component diagram and specific loading/upsert strategy for that stack.