1) Goals & non-goals
Goals
- Serve OLTP (high-QPS point reads/writes, short transactions) and OLAP (large scans/aggregations/joins) on the same logical dataset.
- Keep OLTP latency stable under analytical load.
- Provide bounded-staleness analytics with explicit freshness SLAs.
- Support strong consistency for OLTP, and snapshot-consistent OLAP reads.
- First-class observability and operational safety (routing, backpressure, failure modes).
Non-goals (optional depending on org)
- Cross-region true-active writes (adds complexity); can start with single-writer region + async geo replicas.
2) Reference architecture (components)
- SQL/API Gateway
- Authentication/authorization, connection pooling, query admission control.
- Workload Classifier
- Classifies each request as OLTP / OLAP / mixed, and estimates cost.
- Query Router
- Chooses execution target(s): row shards, column shards, or federated execution.
- Row Store Cluster (OLTP)
- Partitioned row-oriented shards (range/hash), MVCC, secondary indexes.
- Synchronous replication via consensus (e.g., Raft/Paxos) for strong consistency.
- Change Log / CDC Pipeline
- Logical change stream from OLTP WAL/redo log.
- Column Store Cluster (OLAP)
- Column-oriented shards/replicas built from CDC, optimized for scans.
- Columnar segments, zone maps, dictionary encoding, bitmap indexes, etc.
- Metadata & Timestamp Service
- Global monotonically increasing timestamps / commit ordering (or per-partition with safe-time).
- Observability Stack
- Metrics + logs + distributed tracing + query profiles, plus “freshness” monitoring.
- Control Plane
- Placement, rebalancing, autoscaling, config, schema management.
You can deploy row and column on:
- Separate node pools (preferred for isolation), or
- Same nodes with strict cgroups/quotas (acceptable for small deployments).
3) Workload classification (how to decide OLTP vs OLAP)
3.1 Signals
- SQL shape: presence of
GROUP BY, ORDER BY on large sets, window functions, broad joins, subqueries, CTEs.
- Cardinality estimate: predicted rows scanned, join sizes, expected result size.
- Latency objective: API endpoint tag (e.g.,
checkout, dashboard, etl).
- Access pattern: point lookup by PK/unique index vs range scan.
- Runtime feedback: historical stats per query fingerprint (p95 latency, bytes read).
3.2 Classification output
Return a tuple like:
class: OLTP | OLAP | MIXED
cost: estimated CPU/IO/memory
target_freshness: e.g., <= 5s lag or “must be read-your-writes”
resource_tier: interactive | batch | background
3.3 Policy examples
- OLTP if:
- Uses PK/unique index, expected rows < N (e.g., 1k), and no big aggregation.
- OLAP if:
- Expected scanned bytes > threshold, or
GROUP BY across large partitions, or star-schema join.
- MIXED:
- Short OLTP filter + big aggregation; route to column store but possibly use row store for small dimension lookups.
4) Storage layout: row vs column shards (recommended pattern)
4.1 Logical partitioning
Partition tables by:
- Tenant/organization (strong isolation), then
- Time (for event/log tables), then
- Optional hash/range on primary key for hot distribution.
This enables:
- Fast OLTP point access (tenant + key).
- OLAP pruning (tenant + time ranges).
4.2 Row store (OLTP) shard layout
- Row-oriented pages/LSM optimized for writes and point reads.
- MVCC records with commit timestamps.
- Secondary indexes for OLTP access patterns.
- Keep hot working set in memory; rely on WAL for durability.
Best practices
- Avoid too many secondary indexes on heavy-write tables.
- Use covering indexes for critical read paths.
- Keep large text/blob columns off-row if possible.
4.3 Column store (OLAP) shard layout
Two common variants:
Variant A (most common): “Columnar replicas”
- For each logical partition (e.g., tenant+time), maintain a columnar replica built from CDC.
- Store in immutable columnar segments (micro-partitions).
- Background compaction/merge to optimize sort order (e.g.,
(tenant_id, event_time)).
Variant B: “Dedicated column shards”
- Column store is independently sharded (may not align 1:1 with OLTP partitions).
- Offers OLAP flexibility but makes “exact snapshot at timestamp” harder unless carefully coordinated.
Recommended: Variant A for simplicity and predictable freshness.
4.4 “Hot + warm” tiering (optional)
- Recent data (e.g., last 7–30 days) kept in column store “hot” tier for fast dashboarding.
- Older data moved to object storage + query engine (or cheaper nodes) with the same schema.
5) Replication & consistency model
5.1 OLTP replication (row store)
- Consensus-based replication (Raft/Paxos) per shard group:
- 1 leader, 2+ followers (e.g., RF=3).
- Write consistency: commit on majority acknowledgment.
- Read consistency options:
- Linearizable reads from leader (or quorum reads).
- Follower reads allowed if “bounded staleness” acceptable for some endpoints.
5.2 OLAP replication (column store)
- Built from OLTP via CDC (WAL decoding or logical replication).
- Asynchronous relative to OLTP commit; provides bounded staleness.
Guarantees typically:
- Snapshot consistency within column store at a chosen “safe timestamp”.
- At-least-once ingestion with idempotent merge (dedupe by
(primary_key, commit_ts) or change sequence).
- Optional exactly-once with transactional offsets + idempotent segment writes.
5.3 Timestamping / “safe time”
Maintain per-partition:
commit_ts: assigned at OLTP commit.
applied_ts: latest commit timestamp ingested into the column store.
safe_ts: timestamp up to which the column store is complete and queryable consistently.
6) Query routing strategy
6.1 Routing rules (default)
- OLTP queries → row store leader (or quorum).
- OLAP queries → column store, using
safe_ts that satisfies freshness SLA.
- Mixed queries:
- If heavy scan/aggregation: run on column store.
- If needs freshest row-level check (e.g., fraud decision): do a small OLTP lookup first, then OLAP.
6.2 Freshness-aware routing
Given a query with requirement max_lag = X:
- Fetch column store
applied_ts for involved partitions.
- Compute
lag = now_ts - applied_ts.
- If
lag <= X: route to column store.
- Else:
- Option A: wait up to
X_wait for ingestion to catch up (good for dashboards).
- Option B: fallback to row store with strict guardrails (limit scanned bytes / time).
- Option C: return partial/older results with explicit staleness metadata (only if product accepts it).
6.3 Protecting OLTP from analytical fallback
If routing to row store for OLAP fallback:
- Enforce hard limits: max partitions, max rows/bytes, max execution time.
- Use separate “analytical read replicas” of row store (optional).
- Apply admission control so OLTP SLOs remain intact.
7) Freshness SLAs (define, measure, enforce)
7.1 Example SLA tiers
- Interactive dashboards: p95 freshness lag ≤ 5–15s
- Operational reporting: ≤ 1–5 min
- Batch analytics: ≤ 1 hour
- Financial close/audit: must be exact as-of a chosen timestamp (may require wait)
7.2 What to measure
Per table/partition/tenant:
cdc_emit_latency: OLTP commit → CDC record available
ingest_latency: CDC record available → applied to column store
query_safe_lag: now → safe_ts
7.3 Enforcement mechanisms
- Backpressure from column store ingestion (throttle CDC consumers before they fall too far behind).
- Autoscale ingestion workers and column compaction.
- Alert on sustained lag and on “freshness SLO burn rate”.
8) Isolation handling (transactions vs analytics)
8.1 OLTP isolation
Use MVCC:
- Default Snapshot Isolation (SI) for performance.
- Offer Serializable for critical transactions (with higher contention cost).
- Explicit read-write conflict handling and deadlock detection/timeouts.
8.2 OLAP isolation / correctness
Analytics should read a stable snapshot:
- Each OLAP query is executed at a chosen snapshot timestamp
ts_query <= safe_ts.
- Column store ensures segments are consistent up to
ts_query.
8.3 Long-running analytical queries vs MVCC GC
Problem: long queries prevent garbage collection of old versions.
Mitigations:
- In column store: immutable segments + version pruning at segment boundaries.
- In row store: cap OLAP access; don’t run long scans on OLTP leaders.
- Use “time travel retention” policies:
- Keep row-store MVCC history short (minutes-hours).
- Keep column-store history longer if needed (days) with compacted snapshots.
8.4 Read-your-writes (optional)
If an application wants immediate visibility of its own writes in analytics:
- Provide a mode:
- execute OLTP txn → get
commit_ts
- route analytics query with requirement
safe_ts >= commit_ts, optionally waiting
- Or do “delta overlay”: union recent changes from row store (bounded) onto column query (complex, but can reduce waiting).
9) Observability (what to instrument)
9.1 Golden signals
OLTP
- QPS, p50/p95/p99 latency, error rate
- Lock/txn conflicts, deadlocks, aborts
- CPU, mem, disk IO, WAL fsync time
- Replication: leader elections, commit quorum latency
OLAP
- Query queue time, execution time, bytes scanned, rows scanned
- Segment cache hit rate, spill-to-disk, join memory usage
- Compaction backlog and duration
Freshness
applied_ts lag per partition/tenant
- end-to-end lag distributions
- percentage of queries served within freshness SLA
9.2 Tracing & profiles
- Distributed traces through gateway → router → engine.
- Attach:
- query fingerprint, plan hash, chosen engine, snapshot timestamp, partitions touched
- routing reason (classifier output)
- Query profiles stored for slow queries (operator-level timings, bytes).
9.3 Operational dashboards & alerts
- Burn-rate alerts for OLTP latency SLO and freshness SLO.
- Alerts for:
- CDC consumer lag, ingestion failures, schema drift
- replication lag / follower unhealthy
- column compaction backlog exceeding thresholds
- routing anomalies (unexpected OLAP to OLTP fallbacks)
10) Deployment steps (practical rollout)
10.1 Infrastructure
- Provision separate node pools:
oltp-nodes (low-latency SSD, high IOPS)
olap-nodes (CPU-heavy, large RAM, SSD; optionally object store)
ingest-nodes (network + CPU)
- Configure networking, service discovery, secrets, IAM.
10.2 Bring up OLTP first
- Deploy row-store cluster with RF=3, enable MVCC and backups.
- Create schemas, partitioning strategy, indexes.
- Validate OLTP SLOs with synthetic workload.
10.3 Add CDC
- Enable WAL/logical decoding.
- Deploy CDC pipeline (with durable offsets/checkpoints).
- Verify idempotency and ordering assumptions.
- Run initial snapshot/backfill into column store (bulk load), then switch to incremental CDC.
10.4 Deploy column store
- Create column projections/sort keys (tenant_id, time).
- Configure segment size, compaction policy, caching.
- Establish
safe_ts computation and publish metadata.
10.5 Enable router gradually
- Start in observe-only mode: classify queries but still route all to OLTP (or existing system).
- Shadow-read: run OLAP queries on column store in parallel and compare results (sampled).
- Gradually enable routing for:
- known dashboards,
- then read-only endpoints,
- then broader BI access.
- Turn on freshness SLA enforcement + fallbacks.
10.6 Production hardening
- Backups:
- OLTP: PITR via WAL archival + periodic snapshots
- OLAP: segment backups or reproducible rebuild from CDC + checkpoints
- Disaster recovery tests (restore drills).
- Capacity autoscaling rules for ingestion and OLAP.
11) Testing plan (correctness + performance + resilience)
11.1 Correctness
- End-to-end reconciliation:
- For sampled partitions/time windows: aggregate metrics from row store vs column store at the same snapshot timestamp.
- CDC correctness:
- Inserts/updates/deletes, out-of-order delivery, duplicate delivery, schema changes.
- Isolation tests:
- Snapshot consistency for OLAP at
ts_query
- OLTP anomalies (write skew) under SI if used; validate serializable where required.
- Schema evolution:
- Add column, rename, type widen, drop column; ensure CDC and column store handle gracefully.
11.2 Performance
- OLTP benchmark (e.g., TPC-C-like): verify p95/p99 under peak.
- OLAP benchmark (TPC-H-like + your real dashboards):
- bytes scanned, concurrency, queueing behavior, spill rates.
- Mixed workload test:
- ensure OLTP latency stays within SLO when OLAP concurrency spikes.
11.3 Resilience / chaos
- Kill OLTP leaders; verify failover time and no data loss beyond agreed semantics.
- Partition network between CDC and OLAP ingestion; verify lag alarms and recovery.
- Corrupt/lose an OLAP node; verify segment re-replication and query continuity.
- Backpressure tests:
- artificially slow compaction; ensure freshness SLA degrades predictably and routing behaves (wait/fallback).
11.4 Routing & SLA tests
- Synthetic queries labeled with required freshness; verify:
- correct engine selection
- correct waiting behavior
- correct fallback behavior with guardrails
- Validate that no OLAP query can exceed OLTP scan limits when routed incorrectly.
12) Concrete defaults (a good starting point)
- Row store: RF=3, strong writes, SI default + serializable option.
- Column store: async from CDC,
safe_ts tracked per partition.
- Freshness SLA: 15s for interactive dashboards; router waits up to 5s then serves last-safe results (or fails depending on product).
- Isolation: OLAP always uses snapshot
<= safe_ts; never reads directly from OLTP leaders for large scans.
- Guardrails: any query routed to row store must satisfy max-bytes + max-time + max-partitions limits.
- Observability: freshness lag and routing decisions are first-class metrics.
If you share expected scale (QPS, data size/day, query concurrency), tenancy model, and whether you need cross-region reads/writes, I can tailor shard keys, replication topology, and specific SLA numbers and guardrail thresholds.