Database Selection and Trade-offs Questions
Choosing the right database and data platform for a workload: relational versus NoSQL versus specialized stores, managed versus self-hosted, and matching technology to consistency, scale, cost, and query or access-pattern needs. Covers OLTP versus OLAP and transactional-versus-analytical workload splits, polyglot persistence across multiple data stores, structuring an ambiguous selection prompt, naming trade-offs, and defending a recommendation to stakeholders.
Design a hybrid OLTP/OLAP (HTAP) schema to support fast transactional operations (order placement) and low-latency analytics (live dashboards) on the same system. Discuss schema choices (normalized vs denormalized), indexing, how to protect transactional latency under analytic load, consistency models, and whether to use a purpose-built HTAP DB (TiDB, SingleStore) or maintain separate systems with CDC.
Sample Answer
Direct answer
Normalize the transactional core (orders, order items, payments) for correctness, so a checkout can never drift into a partially-updated state, and add a deliberately denormalized, separately-maintained analytic layer, rollup tables or a columnar replica, for the live dashboard, rather than denormalizing the transactional schema itself to serve both. Protect transactional latency by structurally separating where the analytic query executes: a replica, a columnar engine, or an isolated resource pool inside an HTAP database, never the same buffer pool and lock manager checkout writes to.
Structured elaboration
Normalized vs denormalized
Order placement needs a normalized schema (orders one-to-many order_items, a foreign key to payments) so a single update can't leave line items and totals inconsistent. The live dashboard wants pre-aggregated, denormalized rollups (orders per minute by region, say) because recomputing that aggregation from the normalized tables on every refresh means repeatedly scanning the same tables checkout is writing to.
Indexing
The transactional side wants few, narrow, high-selectivity indexes (indexes on columns with enough distinct values that a lookup quickly narrows to a small number of rows, instead of scanning a large chunk of the table) tuned for point lookups and inserts, because every extra index is write amplification (each index has to be updated too, so one logical write turns into several physical writes) on every insert and update. Analytic queries want either a columnar representation, compressed and scanned by column, or purpose-built aggregate tables. That is a fundamentally different access pattern than a small set of B-tree indexes (a sorted tree structure most relational databases use by default, good at point lookups and range scans over rows) can serve well at both ends.
Protecting transactional latency
Resource isolation is the core requirement: (a) a physically separate replica so analytic scans never share a buffer pool (the in-memory cache of recently used data pages) or lock manager (the component that tracks which rows are locked by in-progress transactions) with checkout writes, (b) if using a genuinely HTAP engine, isolate at the engine level (TiDB pairs a transactional row store, TiKV, with a separate columnar replica, TiFlash, and routes analytic queries to TiFlash's nodes so they don't consume TiKV's transactional resources; SingleStore's unified storage still benefits from routing heavy scans to dedicated compute), and (c) query timeouts and resource governors so a runaway dashboard query gets killed rather than starving checkout.
Consistency models
Dashboard reads are usually fine as read-committed (each query only sees data that has already been committed, though two steps of the same query can still see slightly different snapshots, unlike a stricter isolation level), or even bounded-staleness against a replica (orders 5 to 30 seconds old is normal for a live dashboard). Order placement needs full ACID within the checkout transaction: an order and its payment record commit together or not at all. Naming this distinction explicitly in the design, which paths get which guarantee, prevents someone downstream from assuming the whole system is uniformly strongly consistent.
HTAP database vs separate systems with CDC
Choose a purpose-built HTAP database when the dashboard needs to reflect committed writes within single-digit seconds and you want to operate one system instead of two. Choose CDC (change data capture: streaming each committed row change out of the database as an event) into a separate analytic system when the team already runs a mature analytics stack, when tens of seconds to a couple of minutes of dashboard staleness is acceptable, or when the transactional engine is fixed by other constraints (an existing investment, a compliance requirement) and swapping it isn't realistic.
Worked example
-- Transactional core (normalized)
CREATE TABLE orders (
order_id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL,
region TEXT NOT NULL,
status TEXT NOT NULL,
placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE order_items (
order_item_id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(order_id),
sku TEXT NOT NULL,
qty INT NOT NULL,
unit_price_cents BIGINT NOT NULL
);
CREATE INDEX idx_orders_customer ON orders(customer_id);
-- Analytic rollup, maintained out of band (CDC or a scheduled job), never read by checkout
CREATE TABLE orders_per_minute_by_region (
minute_bucket TIMESTAMPTZ NOT NULL,
region TEXT NOT NULL,
order_count BIGINT NOT NULL,
revenue_cents BIGINT NOT NULL,
PRIMARY KEY (minute_bucket, region)
);
The dashboard queries orders_per_minute_by_region, a handful of rows per screen refresh, instead of aggregating the full orders table, so its query cost stays roughly constant as orders grows, and checkout writes only ever touch orders and order_items, never contending with the dashboard's aggregation.
Trade-offs & pitfalls
Over-denormalizing the transactional side itself, embedding computed aggregates directly into orders, trades write-path correctness for read convenience and reintroduces the anomalies normalization exists to prevent. Under-isolating, letting the dashboard query the live orders table "just for now", is the single most common way this design degrades in production: a query that was fine at low volume becomes a lock-contention or cache-eviction problem once order volume climbs. On the HTAP side, only the specific tables the dashboard reads need dual row and columnar treatment; forcing every table in the schema onto the HTAP engine's more constrained feature set buys nothing.
Design the data storage architecture for a social feed service with 10M users and 1B posts. Requirements: personalized feeds with p95 read <100ms, write throughput 50k posts/min, support full-text search over posts, and eventual consistency acceptable for feed freshness. Map query patterns (fanout-on-write vs fanout-on-read) to storage options (wide-column, key-value cache, search engine) and justify replication, caching, and consistency trade-offs.
Sample Answer
Direct answer
Use a hybrid fanout: fanout-on-write (push a new post into every follower's precomputed feed at write time) for the vast majority of accounts, and fanout-on-read (pull the author's recent posts at read time and merge them into the feed) for high-follower accounts. Pure fanout-on-write collapses under the write amplification (one write turning into many downstream writes, here one post turning into one inbox write per follower) of a handful of extremely popular accounts, and pure fanout-on-read makes every ordinary read expensive by fanning out a query per followed account at read time.
Structured elaboration
Query pattern to storage mapping.
- Post storage (durable, high write volume, simple key lookup by post id): a wide-column store (Cassandra/Scylla) with replication factor (RF) of 3, a typical durability/availability choice giving each row three replicas so the loss of one node does not lose data, because posts are write-once, read-many and don't need relational joins.
- Precomputed per-user feed ("inbox"): a key-value cache (Redis, or a wide-column "feed" table keyed by user id holding a sorted list of post ids), because a feed read needs to be a single fast lookup by user id, not a fan-out query computed at read time.
- Full-text search over posts: a dedicated search engine (Elasticsearch/OpenSearch), a genuinely different query shape ("rank posts matching these words") that belongs in neither of the above.
Fanout math (worked). 50,000 posts/min is about 833 posts/sec:
posts_per_min = 50_000
posts_per_sec = posts_per_min / 60
avg_followers = 200 # illustrative average, for order-of-magnitude reasoning
naive_fanout_writes_per_sec = posts_per_sec * avg_followers
celeb_followers = 5_000_000
celeb_single_post_fanout = celeb_followers # one post, fanned out synchronously
print(f"posts/sec: {posts_per_sec:.1f}")
print(f"naive fanout-on-write at {avg_followers} avg followers: {naive_fanout_writes_per_sec:,.0f} inbox writes/sec")
print(f"a single post from a {celeb_followers:,}-follower account: {celeb_single_post_fanout:,} inbox writes for ONE post")
posts/sec: 833.3
naive fanout-on-write at 200 avg followers: 166,667 inbox writes/sec
a single post from a 5,000,000-follower account: 5,000,000 inbox writes for ONE post
The steady-state average (about 167,000 inbox writes/sec at this illustrative follower count) is a large but achievable rate for a wide-column store or Redis cluster built for high write throughput. The problem is the TAIL: one post from a 5-million-follower account would generate 5 million inbox writes in one event, dwarfing the steady-state load. For accounts past a monitored follower-count threshold, don't fan out on write; merge their few recent posts into a requesting user's feed at READ time instead, cheap because there are few of them and they are easy to cache. This hybrid is the standard, well-documented pattern large-scale feed systems use for exactly this problem.
Consistency and caching. Eventual consistency is explicitly acceptable per the requirements, so post-create can return immediately while fanout happens asynchronously in a background worker, and Redis in front of the wide-column feed store absorbs the read-hot top-of-feed page (well inside the p95 under 100ms budget; a cache miss falling through to the wide-column store is still fast, single-digit to tens of milliseconds).
flowchart TD
W[New post] --> C[(Cassandra: posts, RF=3)]
W --> F{Author follower count}
F -- normal account --> FW[Async fanout worker]
FW --> Redis[(Redis / wide-column feed store: per-user inbox)]
F -- celebrity account --> Skip[Skip fanout-on-write]
W --> Search[(OpenSearch: async index)]
Reader[Feed read] --> Redis
Reader --> Merge[Merge in celebrity posts at read time]
Trade-offs & pitfalls
The celebrity threshold needs an explicit, monitored cutover, a follower-count boundary that routes an account from fanout-on-write to fanout-on-read, or the hot-write problem reappears in production the first time an ordinary user suddenly goes viral. Full-text search staleness (posts indexed asynchronously) means a just-posted message might not be searchable for a few seconds, acceptable under the stated eventual-consistency tolerance, but worth stating explicitly rather than assuming.
You must evaluate three candidate databases for a write-heavy leaderboard system: Redis (in-memory), Cassandra (wide-column), and PostgreSQL (disk-backed). Define benchmark scenarios (writes/sec, reads/sec, read-after-write latency, data size), key failure modes to test, and what metrics and SLOs you would use to pick the right platform.
Sample Answer
Direct answer
Expect Redis to win a leaderboard-shaped write-heavy benchmark, because its sorted-set data structure is purpose-built for exactly this access pattern, with Cassandra as the fallback once the working set genuinely outgrows what fits comfortably in memory, and PostgreSQL as the control that will most likely lose on raw write throughput but establishes the transactional-safety baseline the other two are measured against. That expectation is a hypothesis, not the answer: the actual answer to "evaluate three candidates" is the benchmark design below, built so the result is decided by measurement, not by which system sounds best on paper.
Structured elaboration
Benchmark scenarios to define, each with an explicit target, not a vague description.
| Dimension | What to define | Illustrative target for this exercise |
|---|---|---|
| Writes per second | Sustained score-update rate during a realistic peak (a live event, a tournament) | See worked example: derived from a stated player and update-rate assumption |
| Reads per second | Leaderboard views (top-N plus "my rank") during the same peak | Derived from a stated viewer-to-player ratio |
| Read-after-write latency | Time from a score update to that update appearing in a subsequent top-N read | Under 1 second at the 99th percentile (p99), a reasonable real-time-leaderboard expectation |
| Data size | Number of distinct players in the working set, and average bytes per entry | Drives whether the working set fits the tested memory budget, the central question for Redis specifically |
Failure modes to test, one per candidate plus one cross-cutting. Node or primary failure mid-write-burst: for Redis, verify whether a failover (the automatic process of promoting a standby replica to primary and redirecting traffic when the current primary goes down) during an unacknowledged asynchronous replication window can lose the most recent writes, and whether that risk is acceptable or needs to be closed with a stronger write-acknowledgment setting (accepting the latency cost of waiting for a replica to confirm). For Cassandra, verify behavior under a network partition: does it continue accepting writes per the configured consistency level, and do replicas correctly reconcile once the partition heals. For PostgreSQL, verify failover behavior with a managed or self-managed replication topology and measure how long writes are actually unavailable during the failover window. Cross-cutting: run a genuine network partition or node-kill during the sustained peak load from the writes/reads targets above, not against an idle system, since failure behavior under load is the behavior that matters.
Metrics and service-level objectives (SLOs) to observe. Write latency, p50 and p99. Read latency, p50 and p99. Read-after-write staleness distribution (not just an average, the tail is what a user actually notices). Replication lag under load. Error rate during the fault-injection window. Time to return to SLO-compliant behavior after a failure resolves. And one candidate-specific early-warning metric each: for Redis, memory headroom against maxmemory and the active eviction policy (if the working set exceeds available memory, Redis evicts keys per policy, commonly least-recently-used, which can silently and incorrectly drop leaderboard entries if the eviction policy is not deliberately scoped away from leaderboard keys); for Cassandra, compaction backlog (a growing backlog under sustained high write rate is the leading indicator that read latency is about to degrade, well before it visibly does); for PostgreSQL, table and index bloat ratio from autovacuum lag (a write-heavy pattern that repeatedly updates the same rows, exactly what leaderboard score updates do, is the classic case that causes PostgreSQL's multi-version concurrency control, MVCC, to accumulate dead row versions faster than autovacuum reclaims them, degrading both read and write latency over time if unaddressed).
Why these three failure modes are not interchangeable, and why they matter more than the raw throughput numbers. A benchmark that only measures steady-state throughput will make all three candidates look reasonable; the failure modes above are each a specific, well-known weak point of a write-heavy pattern on that particular engine, and a benchmark that skips them will not catch the actual production incident each engine is prone to.
Worked example
Derive the writes/sec and reads/sec targets from a stated scenario, and check Redis's working-set memory budget against a stated player count, since memory headroom is the single most consequential capacity question for a Redis-based design.
# benchmark target derivation for a write-heavy leaderboard.
players = 5_000_000
updates_per_player_per_day = 40 # match/score events per active player per day
writes_per_day = players * updates_per_player_per_day
writes_per_sec_avg = writes_per_day / 86400
peak_multiplier = 6 # evening/event-driven peak concentration
writes_per_sec_peak = writes_per_sec_avg * peak_multiplier
print(f"avg writes/sec = {writes_per_sec_avg:,.0f}, peak writes/sec (x{peak_multiplier}) = {writes_per_sec_peak:,.0f}")
# Redis working-set sizing for a large leaderboard.
lb_players = 20_000_000
bytes_per_entry = 200 # member id + score + sorted-set node overhead, illustrative
working_set_gb = lb_players * bytes_per_entry / 1e9
replication_factor = 2 # primary + 1 replica for HA
headroom = 1.3
total_ram_gb = working_set_gb * replication_factor * headroom
print(f"working set = {working_set_gb:.1f} GB for {lb_players:,} players")
print(f"RAM budget with {replication_factor}x replication and {headroom}x headroom = {total_ram_gb:.1f} GB")
# avg writes/sec = 2,315, peak writes/sec (x6) = 13,889
# working set = 4.0 GB for 20,000,000 players
# RAM budget with 2x replication and 1.3x headroom = 10.4 GB
Two results worth acting on. First, peak write load (about 13,900 writes per second under these stated assumptions) is well within what all three candidates can sustain in isolation; the benchmark's value is in the failure-mode and tail-latency behavior at that load, not in whether any of the three can technically keep up. Second, a 20-million-player leaderboard's working set is only about 4 gigabytes, comfortably fitting in a single modestly sized Redis instance with room to spare for replication and headroom, well under commonly available managed-instance memory tiers. The real trigger for moving off Redis toward Cassandra is not this leaderboard's size, it is a leaderboard an order of magnitude or two larger, or one that needs to retain full historical score events (not just current standings) indefinitely, which no longer fits an in-memory design economically.
Trade-offs & pitfalls
- Benchmarking only steady-state throughput. All three candidates will look acceptable; the failure modes above are where the real differentiation, and the real production risk, actually lives.
- Assuming Redis's async replication failover is safe by default. It is not, without an explicit stronger write-acknowledgment configuration, which trades some write latency for the durability a leaderboard's ranking correctness actually needs.
- Missing a Cassandra compaction backlog until read latency has already visibly degraded. Compaction backlog is a leading indicator specifically because it degrades before the symptom (slow reads) becomes obvious; alert on the backlog metric itself, not just on read latency.
- Treating PostgreSQL's bloat risk as a generic "Postgres is slower" conclusion, rather than the specific, addressable cause it is: hot-row updates outrunning
autovacuum. Tuningautovacuumaggressiveness for the specific hot table, or restructuring the update pattern, is a real fix, not a reason to dismiss PostgreSQL outright for smaller-scale versions of this workload. - Setting the read-after-write latency SLO too strictly for the actual product requirement. A live global leaderboard tolerating roughly a second of staleness is normal and expected; over-specifying "instant" consistency here adds real engineering cost for a UX improvement users are unlikely to notice.
For telemetry at 500k writes/sec, compare wide-column stores (Cassandra/Scylla), document stores (MongoDB), and key-value stores (DynamoDB) in terms of write scalability, compaction, consistency, ability to run aggregations, and operational overhead. Which would you recommend and why? Include mention of data modeling patterns to keep throughput high.
Sample Answer
Direct answer
Recommend Cassandra or Scylla (a Cassandra-API-compatible engine built for higher single-node throughput) at this scale: 500,000 writes/sec sustained sits deep in log-structured merge-tree (LSM-tree) territory, the storage-engine class purpose-built for high, mostly-append write rates. DynamoDB or MongoDB can technically be scaled to absorb this rate, but at materially higher metered cost (DynamoDB) or greater operational fragility for this specific write-dominant, low-query-complexity shape (MongoDB).
Structured elaboration
Write scalability. For DynamoDB:
writes_per_sec = 500_000
wcu_limit_per_partition = 1000
min_partitions = writes_per_sec / wcu_limit_per_partition
print(f"minimum partitions at the per-partition WCU limit: {min_partitions:.0f}")
print(f"partitions with 2x headroom: {min_partitions * 2:.0f}")
minimum partitions at the per-partition WCU limit: 500
partitions with 2x headroom: 1000
This is technically achievable, but DynamoDB's pricing is per request or per provisioned capacity unit, so cost scales linearly and directly with this write rate with no "buy cheaper hardware" lever, unlike a self-managed or reserved-capacity cluster where the marginal cost of another write is amortized node capacity. MongoDB needs a sharded cluster with a well-distributed shard key; its WiredTiger storage engine uses B-tree-like pages (a sorted, tree-shaped on-disk index structure that has to split and rebalance pages as new keys are inserted, each split costing a random disk seek) with a write-ahead journal rather than a pure LSM-tree, so sustained extreme write rates cost more in disk I/O per write at the same throughput, and checkpoint and eviction behavior needs careful tuning under load this heavy to avoid write stalls. Cassandra/Scylla's LSM-tree writes (an in-memory buffer plus an append-only commit log, no read-before-write, no random-access disk seeks on the write path) are the cheapest write shape of the three per unit of hardware; Scylla in particular is built with a shard-per-core architecture specifically to push single-node write throughput higher than Cassandra's JVM-based engine.
Compaction. Compaction (the background process that merges a storage engine's accumulated on-disk write files into fewer, larger ones, reclaiming space) is central to running an LSM-tree engine at this rate; Cassandra/Scylla's choice of compaction strategy matters enormously; TimeWindowCompactionStrategy for TTL'd telemetry keeps compaction cost roughly constant per time window instead of growing with total data volume, as covered for the wide-column time-series schema above. MongoDB's WiredTiger doesn't expose an equivalent choice the same way; its checkpoint and eviction behavior is mostly self-tuning but less controllable under sustained extreme write load. DynamoDB hides compaction entirely as an AWS-managed detail, a pro (nothing to tune) and a con (nothing to tune when it doesn't behave the way the workload needs).
Consistency. All three offer tunable-ish per-request consistency: Cassandra's ONE/QUORUM/LOCAL_QUORUM/ALL (with W + R > RF, write consistency plus read consistency greater than the replication factor, giving a read-your-writes guarantee); DynamoDB's eventually- versus strongly-consistent reads; MongoDB's read and write concern levels. Telemetry ingestion almost never needs strong consistency on the write side (nobody needs a strongly-consistent read of a metric point immediately after it was written), so all three can run their cheapest, fastest consistency setting for ingestion.
Ability to run aggregations. None of the three is an OLAP (online analytical processing, a query shape built for scanning and aggregating large historical datasets) engine. "Average CPU across all hosts for the last hour," run against the raw ingestion store in any of the three, means either a full scan (slow, expensive) or maintaining pre-aggregated rollup rows written alongside the raw data, a data-modeling pattern, not a database feature. At this scale, the honest architecture streams the ingested data (for example via Kafka) into a purpose-built OLAP or time-series aggregation engine downstream, and treats the wide-column, key-value, or document store as the write-path buffer, never the analytics engine.
Operational overhead. DynamoDB: lowest (fully managed), at the highest metered dollar cost for this write rate and the least tuning control. Cassandra/Scylla: highest self-management burden (repair scheduling, compaction tuning, capacity planning) unless bought as a managed service, but the best cost-to-throughput ratio for a workload this write-heavy. MongoDB: middling; sharding a cluster to 500,000 writes/sec is a real operational undertaking, and, per the compaction discussion above, not the storage engine best matched to this specific shape.
Data modeling patterns to keep throughput high. Time-bucketed partition or shard keys (as in the time-series schema above) to avoid unbounded or hot partitions; batching writes per partition where the client library supports it, to amortize per-request overhead; avoiding secondary indexes on the hot ingestion table entirely, building them if needed on a downstream rollup table instead, since maintaining a secondary index on every write is exactly the kind of extra cost that caps sustainable write throughput first.
Mapping adjacent telemetry-shaped workloads (sessions, feature store, logs). "High write rate" alone does not dictate the store, the QUERY shape does. Session data (small blobs, read and written whole by session id, expiry-driven) fits a key-value store like DynamoDB best, not wide-column, because there is no time-range scan need. An online feature store (point lookups by entity id at read time, needing single-digit-millisecond latency) fits an in-memory key-value layer like Redis in front of a durable store, not wide-column, because the access pattern is single-key point reads, not time-ordered scans. Application logs (append-heavy, queried mostly by time range and free text) fit wide-column for the raw retention tier plus a search engine for the free-text query need, the closest of the three to telemetry's own shape.
Worked example
The DynamoDB partition math above (500 minimum, 1,000 with headroom) is the only precisely derivable number here, since it follows directly from a documented AWS limit; sizing a Cassandra or Scylla cluster to 500,000 writes/sec is properly a hardware-benchmark exercise against real nodes, not something to predict analytically, so it is intentionally not estimated with a specific node count here.
Trade-offs & pitfalls
The single biggest mistake at this scale is putting a secondary index or an unbounded partition on the hot ingestion path "just in case a dashboard needs it later," which caps throughput well below what the storage engine could otherwise sustain. The second is treating the ingestion store as if it were also the analytics store: at 500,000 writes/sec, the honest architecture always has a downstream OLAP hop, and pretending otherwise just moves the pain to whoever runs the first slow aggregation query against the live ingestion table.
You operate a MySQL cluster that handles mostly heavy writes plus occasional analytical queries. Compare the InnoDB and MyISAM storage engines on concurrency control, crash safety, and transactional support. Recommend an engine and indexing approach for this workload, and describe how you would provision storage and maintenance so the analytical queries do not interfere with the write path.
Sample Answer
Direct answer
Use InnoDB, not MyISAM, for this workload. MyISAM's table-level locking means every write blocks every other read and write against that table, which is disqualifying for a workload described as mostly heavy writes, while InnoDB's row-level locking plus MVCC (multi-version concurrency control: readers see a consistent snapshot of the data without blocking writers, and writers don't block readers) is exactly the property that lets an occasional analytical query run without stalling the write path.
Structured elaboration
Comparing the two engines directly, per current MySQL documentation:
| Property | InnoDB | MyISAM |
|---|---|---|
| Locking granularity | Row-level | Table-level: a single writer blocks all other readers and writers on that table |
| Concurrency control | MVCC, so most reads, including analytical SELECTs under the default REPEATABLE READ isolation level (a transaction sees a consistent snapshot of the data as of when it started, unaffected by other transactions committing in the meantime), take a consistent snapshot without locking | No MVCC and no row-level locking option at all |
| Crash safety | Fully crash-safe via a redo log (a sequential on-disk record of every change, replayed to restore the database after a crash) and a doublewrite buffer (a safety copy of each page written just before the real write, so a crash in the middle of writing still leaves a good copy to recover from), recoverable to a consistent state after a crash | No transaction log; on-startup auto-check and repair via myisam_recover_options is a best-effort repair of whatever was on disk, not a guarantee no committed-looking write was lost |
| Transactional support | Fully ACID-compliant (atomicity, consistency, isolation, durability: a transaction either fully completes or fully rolls back, and committed data survives a crash), multi-statement transactions, foreign keys | Neither: every statement auto-commits independently with no rollback and no foreign keys |
| Current status | The default storage engine in current MySQL | Still supported, but current documentation frames it as fit for narrow cases: read-heavy or read-only, compressed tables |
Given this, InnoDB is the only reasonable choice for a heavy-write workload. MyISAM's remaining legitimate cases, per current documentation, don't describe this one.
Indexing approach
Keep the number of secondary indexes on the write-heavy tables deliberately small, since InnoDB maintains every secondary index synchronously on every insert and update, so each additional index is real write amplification (extra physical writes the database performs beyond the one logical row change you made). Add a covering index (one that includes every column the analytical query needs) specifically shaped for the analytical query only if it's a small, stable, repeated query, so it can be served from the index without visiting the full row, rather than adding broad indexes speculatively.
Provisioning so analytics doesn't interfere with the write path
InnoDB solves the locking problem but not the I/O and cache contention problem: a large aggregation still consumes buffer pool cache (InnoDB's in-memory cache of data pages, kept to avoid re-reading from disk) and disk I/O that writes also need. The concrete move is to run analytical queries against a replica, an InnoDB replica receiving the same writes via replication, rather than the primary, so the analytical query's I/O and cache pressure lands on a separate instance. Size the replica's InnoDB buffer pool independently, for the analytical working set, which is often close to the whole table, unlike the primary's buffer pool, which mainly needs the recently written "hot" rows. Set a statement timeout on the analytical connection so a runaway ad hoc query on the replica can't grow unbounded and starve the replication apply thread, which would otherwise let the replica's data go stale for everyone.
Worked example
-- InnoDB is the MySQL 8.4 default, but be explicit
CREATE TABLE events (
event_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
device_id BIGINT UNSIGNED NOT NULL,
event_type VARCHAR(32) NOT NULL,
payload JSON NOT NULL,
created_at DATETIME NOT NULL
) ENGINE = InnoDB;
-- One narrow secondary index actually used by the write-time lookup pattern
CREATE INDEX idx_events_device_created ON events (device_id, created_at);
On the read replica used for analytics: SET SESSION max_execution_time = 30000; kills any single query running past 30 seconds, and the replica's innodb_buffer_pool_size is provisioned larger relative to instance memory than the primary's, because the primary mostly needs to cache the current write-hot region while the replica needs to cache whatever the analytical queries scan, often a much larger working set.
Trade-offs & pitfalls
Routing analytics to a replica introduces replication lag, so analytical numbers are always slightly behind the primary; this needs to be an accepted, stated freshness bound, not a surprise discovered later. If the "occasional" analytical queries grow into a regular reporting workload with dozens of dashboards, a single InnoDB replica stops being the right tool, and it's time to reconsider this same separation decision with a genuinely columnar system rather than continuing to add replicas as the only lever. Don't assume InnoDB alone fixes everything: a write-heavy table carrying eight redundant secondary indexes for old query patterns nobody uses anymore will still have a slow write path. InnoDB's row-level locking removes MyISAM's specific problem, it doesn't remove general write amplification from over-indexing.
Unlock Full Question Bank
Get access to all Database Selection and Trade-offs interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.