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.
Describe wide-column stores (e.g., Cassandra, HBase) and how they differ from relational databases and document stores. What workloads and access patterns are best suited to wide-column stores? Give a simple example schema for storing time-series metric data in a wide-column store.
Sample Answer
Direct answer
A wide-column store organizes data as rows identified by a partition key, with each row holding a flexible, sparse set of columns grouped into column families and physically sorted by a clustering key. That makes it fundamentally different from a relational table (fixed columns, strong joins and transactions) and from a document store (one nested object per key, with rich indexing inside it but no native cross-record ordering guarantee). This shape is purpose-built for write-heavy, mostly-append, time-ordered data accessed by a known key plus a range, exactly the profile of time-series metrics.
Structured elaboration
Wide-column vs relational vs document. A relational database is schema-first with strong multi-table joins and transactions and indexes on any column, but a poor fit for extremely high, mostly-append write rates, because B-tree indexes (the sorted, tree-shaped on-disk index structure most relational databases use to keep rows quickly findable by key) get expensive to maintain under sustained inserts at scale: each insert does a random disk seek to the page holding its key range, and once that page is full the insert forces a page split that rewrites and rebalances part of the tree, the opposite of the sequential, no-seek writes the LSM-tree design below uses. A rigid schema also resists the sparse "some rows have these columns, others don't" shape common in telemetry (not every metric carries every tag). A document store shares wide-column's flexible per-record schema, but organizes around one whole nested object per key with rich intra-document indexing; wide-column instead organizes around many ROWS sharing one partition, each row a flat (though sparse) set of columns sorted by a clustering key, optimized for "give me a sorted range of rows for this partition" rather than "give me documents matching this nested filter." Cassandra, HBase, and Bigtable-family engines use a log-structured merge-tree (LSM-tree) storage engine: writes go to an in-memory buffer plus an append-only commit log, later flushed to immutable files on disk and merged by a background process called compaction. This makes sustained high write throughput cheap, since there is no in-place random-write disk seeking, at the cost of read amplification (a read may need to check the in-memory buffer plus several on-disk files), managed by choosing a compaction strategy.
Best-suited workloads. Time-series metrics, event and activity logs, IoT sensor readings, and messaging or chat history all share "high write rate, data naturally ordered by time, queries are almost always this key plus a time range," rarely arbitrary cross-entity joins.
Example schema: time-series metrics (Cassandra CQL).
CREATE TABLE metrics (
metric_name text,
host text,
bucket_hour timestamp,
ts timestamp,
value double,
PRIMARY KEY ((metric_name, host, bucket_hour), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
AND compaction = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'HOURS', 'compaction_window_size': 1}
AND default_time_to_live = 2592000;
The partition key is (metric_name, host, bucket_hour), bucketed by hour so no single partition grows unbounded as points keep arriving; an all-time partition per host would eventually become an oversized, hot partition, the same hotspot failure mode DynamoDB has under a different name. The clustering key ts DESC gives sorted, most-recent-first range scans for free.
SRE operational behavior: compaction and garbage collection (GC) for telemetry retention. TimeWindowCompactionStrategy (TWCS) groups on-disk files by the time window they cover and compacts within a window, so an entire window can be dropped WHOLESALE once every row in it has passed its TTL, rather than being rewritten row by row the way SizeTieredCompactionStrategy (Cassandra's older default) would; this is specifically why TWCS is the documented, recommended strategy for TTL'd time-series data. The retention gotcha to know: gc_grace_seconds (a per-table setting, commonly defaulting to 10 days) controls how long TOMBSTONES, the markers left behind for expired or deleted rows, are retained before being permanently purged during compaction, so disk usage will NOT drop immediately at the TTL boundary, only after this grace window has also passed. If node repairs (the anti-entropy process that reconciles replicas) are not run within that grace window, deleted data can even reappear on an under-repaired replica, a well-known Cassandra operational hazard. Telemetry tables with short retention commonly tune gc_grace_seconds down, since a high-volume, low-per-row-value metrics table is a lower risk to under-repair than user data, specifically to reclaim disk sooner.
Trade-offs & pitfalls
Choosing SizeTieredCompactionStrategy for a TTL'd time-series table wastes disk and CPU rewriting data that is mostly about to expire anyway; TWCS is the correct default for this shape. An unbounded partition key (no time-bucketing) is the single most common wide-column schema mistake for time-series data, and it reproduces the same hot-partition failure seen across every store in this domain.
Your team must decide between managing a self-hosted database vs using a managed cloud DB service. List operational responsibilities each option imposes, and describe how you would quantify 'operational burden' and compute a cost comparison beyond pure dollar cost (include time-to-recovery, maintenance windows, and staffing).
Sample Answer
Direct answer
Break "operational burden" into pieces that can each carry a real number, rather than treating it as one vague feeling. Three separable figures: a staffing floor, the minimum headcount genuinely needed to cover the operational responsibilities safely around the clock; time-to-recovery, the realistic duration from primary failure to restored service, which depends on trained people and rehearsed runbooks as much as on the software; and a maintenance-window tax, the recurring hours per month spent patching, upgrading, and capacity planning that produce no new product value but are required to keep the system safe to run. Each converts to a dollar figure, which is what makes operational burden comparable to a managed service's sticker price instead of an unquantified impression.
Structured elaboration
The raw list of responsibilities a self-hosted database imposes, before quantifying anything: operating-system and engine patching; backup execution and, critically, restore testing, since an untested backup is not a proven recovery capability; replication and failover (automatically switching traffic to a healthy standby when the primary node fails) configuration plus practice drills; capacity planning for storage, throughput (the rate of reads and writes the system can sustain), and connections; security hardening and access review; monitoring and alerting setup and tuning; and incident response and on-call.
Staffing floor. Sustainable around-the-clock coverage, avoiding burnout and avoiding a single person being the only one who can respond correctly, realistically needs a rotation of several people, not one, even if a single "primary" owns the system day to day.
Time-to-recovery. Treat this as a function of preparedness, not of hardware. A team that has never rehearsed a failover has a materially worse real-world recovery time than whatever number a runbook claims, regardless of what the database software's own failover mechanics are capable of on paper. That is why time-to-recovery belongs in the staffing and process side of this calculation, drills, runbook maintenance, practiced incident response, rather than being treated as a database feature.
Maintenance windows. Every patch or upgrade cycle that needs a maintenance window, or careful zero-downtime orchestration to avoid one, recurs monthly to quarterly for the system's entire lifetime. The hours spent planning, executing, and validating each one are an ongoing tax that should be budgeted as recurring headcount time, not a one-off project cost.
Worked example
All inputs stated so the arithmetic reproduces exactly. Assume a fully loaded senior database administrator costs $190,000 per year, salary, benefits, and overhead combined, a stated assumption, and that safe around-the-clock coverage needs 4 people in rotation. Self-managed staffing floor: 4 x $190,000 = $760,000 per year. A managed service still needs some in-house database expertise, schema design, query tuning, and capacity planning a provider does not do, estimated here as one senior engineer allocated to database concerns, plus the managed instance's own list price, a stated assumption of $84,000 per year for a representative multi-availability-zone, mid-size managed cluster. Managed total: $84,000 + $190,000 = $274,000 per year. The staffing-driven gap alone: $760,000 - $274,000 = $486,000 per year in favor of managed, before adding the self-managed side's maintenance-window hours and drill time, which are real but depend too much on a specific team's cadence to price honestly here, so this worked example stops at the staffing floor rather than inventing a further number.
Trade-offs and pitfalls
A pitfall is comparing only sticker prices, self-hosted compute cost against managed instance price, and concluding self-hosting is cheaper, since raw compute genuinely can be cheaper self-hosted. The staffing figure above is what closes or reverses that gap, and it is the number most naive cost comparisons leave out entirely.
A second pitfall is assuming a small team can simply absorb database on-call alongside its regular work at no real cost. It shows up instead as slower feature delivery and eventual burnout or turnover, both real costs that are just harder to see on a spreadsheet.
What changes the calculus: an organization that already has a well-staffed database reliability function for other reasons, running several large self-hosted systems, so the rotation is shared and amortized across them. The marginal staffing cost of one more self-hosted system there is much lower than this worked example's from-scratch figure, which is exactly why this decision should be made per organization rather than from one universal rule.
You inherit a backend using a single relational DB that occasionally causes maintenance windows. Propose an incremental modernization roadmap over 12 months to improve availability and scalability while minimizing risk. Include milestones, datastores to introduce, and metrics to measure progress.
Sample Answer
Direct answer
Modernize in four roughly quarter-long stages, each one shippable and reversible on its own, moving from "reduce load on the single database" to "remove the database as a single point of failure" to "give specific workloads their own store" to "prove the new architecture under real failure." Trying to jump straight to a target polyglot architecture in one project is the riskiest version of this roadmap; sequencing it so every stage is independently valuable means the team keeps shipping and keeps a working system even if a later stage gets delayed or cut.
Roadmap
Months 1-3: reduce load without adding new systems. Add a read replica (a copy of the database, kept in sync with the primary, that only serves read queries) and route read-only traffic to it, add a cache (Redis) in front of the hottest read queries, and instrument the database with the monitoring needed to actually see what's causing the maintenance windows (long-running migrations, lock contention, a specific slow query pattern, vacuum/bloat buildup: bloat is wasted space left behind by old, no-longer-needed row versions, and vacuum is the background process, native to databases like Postgres, that reclaims it). Milestone: read replica live and serving a measured percentage of read traffic; maintenance-window root cause identified with data, not guesswork. Metric: reduction in average query latency and load on the primary, and a documented root cause for the existing maintenance windows.
Months 4-6: remove single points of failure in the primary. Move to a managed high-availability configuration (automatic failover to a standby) if not already in place, and start decomposing the riskiest maintenance operations (schema migrations, large backfills) into online, zero-downtime techniques instead of the blocking operations likely causing the windows today. Milestone: a failover has been tested (not just configured) and completes within a defined time budget; at least one previously blocking maintenance operation now runs online. Metric: mean time to recover from a primary failure, measured in a drill, and number of maintenance windows still required per month (target: trending down from whatever the current baseline is).
Months 7-9: introduce a second store for the workload that benefits most. Using the root-cause data from stage 1, pick the single highest-value split: commonly, moving heavy read-mostly or full-text-search traffic to a purpose-built store (a search engine, or a read-optimized cache layer), or moving an analytics/reporting workload off the primary entirely via change data capture (CDC: streaming committed database changes as events) into a small warehouse. This is deliberately one new store, not several, to keep the risk and the learning curve bounded. Milestone: the chosen workload is fully served from the new store in production, with the old path removed, not left running in parallel indefinitely. Metric: the specific latency or load improvement that was the stated goal of picking that workload first.
Months 10-12: validate under real failure, then decide the next split. Run a deliberate failure drill against the now-partially-decomposed system (kill the primary, kill the new secondary store, and check both recovery paths), and use everything learned in stages 1-3 to decide whether a second workload split is warranted or whether the system has reached a stable, "good enough" state. Milestone: a documented failure drill with measured recovery times for both stores. Metric: availability over the full 12 months, measured against the baseline from before the roadmap started, and a written recommendation for whether to continue splitting workloads in year two.
Trade-offs and pitfalls
- Resist decomposing everything in one project. Each new store is a new thing to monitor, upgrade, and be paged for; splitting incrementally and proving each stage under real failure before moving to the next is what keeps this roadmap low-risk relative to a big-bang rearchitecture.
- Don't skip the root-cause step in stage 1. A team that jumps straight to "add a cache" or "split out analytics" without first measuring what's actually causing the maintenance windows risks solving the wrong problem and still having the windows a year later.
- A read replica and a cache reduce load, but they don't remove the primary as a single point of failure. Stage 2 exists because stage 1 alone can create a false sense of resilience while the actual availability risk (the primary going down) is untouched.
- Every milestone above is deliberately measurable, not just "done." A roadmap stage that can't point to a number (latency, recovery time, load percentage) invites the temptation to declare victory without verifying it, which is exactly the failure mode a 12-month, low-risk-by-design roadmap is meant to avoid.
You must choose between PostgreSQL and MongoDB for an application with flexible JSON fields, occasional complex joins, and multi-entity transactions. Define evaluation criteria including query patterns, transactions, index support, operational expertise, scaling needs, and provide a recommendation plus a migration plan if choosing one over the other.
Sample Answer
Direct answer
Recommend PostgreSQL, using JSONB columns (a binary JSON column type that stays queryable and indexable) for the flexible fields, over MongoDB for this specific combination of requirements, because "occasional complex joins" and "multi-entity transactions" are exactly PostgreSQL's strengths and MongoDB's comparative weak points, while PostgreSQL's JSONB support gives most of the schema flexibility the question is asking for almost for free. That recommendation flips if the flexible fields genuinely dominate the workload (most fields are dynamic, joins and multi-entity transactions are rare, and the system needs to scale writes horizontally past what a single PostgreSQL primary can absorb), in which case MongoDB becomes the better default.
Structured elaboration
Why the two named requirements favor PostgreSQL specifically. MongoDB has supported multi-document ACID transactions since version 4.0, extended across sharded clusters since 4.2, so "MongoDB cannot do transactions" is an outdated objection. The real, current gap is cost and capability, not existence: a multi-document transaction in MongoDB is a heavier, more deliberately-invoked operation than PostgreSQL's native, always-on transactional model, and MongoDB's join mechanism (the $lookup aggregation stage) is meaningfully less capable and less performant than a relational query planner's native multi-way join, especially once more than two collections are involved. For a workload where joins and multi-entity transactions are a stated, real requirement, even an "occasional" one, PostgreSQL is answering the requirement natively where MongoDB is answering it through a heavier mechanism.
Where JSONB gets you most of MongoDB's advantage without giving up the relational strengths. A JSONB column holds a schemaless document inside an otherwise ordinary relational table row. It can be indexed (commonly with a Generalized Inverted Index, GIN, which supports efficient containment and key-existence queries against the JSON structure) and queried with operators for containment, path extraction, and key lookup, all inside standard SQL, alongside standard columns and standard joins to other tables. The result is a table that behaves relationally where the data is relational, and flexibly where it is not, in the same row.
Evaluation criteria, both directions.
| Criterion | Favors PostgreSQL + JSONB | Favors MongoDB |
|---|---|---|
| Query patterns | Multi-table joins are common or occasional but real | Nearly all reads are single-document, self-contained |
| Transactions | Multi-entity, all-or-nothing operations are common | Transactions are rare, mostly single-document writes |
| Index support | GIN indexes on JSONB cover the needed containment/path queries | Deeply nested, highly varied query patterns across many different flexible shapes |
| Operational expertise | Team already runs and understands PostgreSQL | Team has existing MongoDB operational depth |
| Scaling needs | Read replicas and a single well-sized primary are sufficient | Genuine need for horizontal write scaling past one primary |
Migration plan, PostgreSQL direction (the recommended default here). Identify the genuinely relational entities (users, orders, whatever has real foreign-key relationships and needs real joins) and normalize those into standard tables. Put the dynamic, variable-shaped attributes into a JSONB column on the relevant table, rather than either a wide sparse table or an entity-attribute-value pattern. Add a GIN index on the JSONB column scoped to the actual query patterns the application uses against it (containment queries need a different index configuration than path-based lookups; verify which the application needs before indexing broadly).
Migration plan, MongoDB direction (if the flip condition applies). Even though the schema is intentionally flexible, define an explicit schema-validation ruleset (MongoDB's $jsonSchema validator) rather than leaving every collection fully unconstrained; an unconstrained flexible schema drifts silently over time as different code paths write slightly different shapes, and the validator catches that drift at write time instead of letting it surface later as an application bug.
Two worked scenarios that both look "flexible-schema" but land on different sides of the recommendation.
Evolving-schema documents (for example, a product catalog where attributes vary wildly by category and change often). This is the strongest case for a document-shaped model: catalog items rarely need multi-entity transactions (updating one product's attributes is a self-contained operation), and cross-category joins are rare by nature (a shoe's size chart has nothing to join against a book's page count). If a catalog service is the entire system, MongoDB, or PostgreSQL with JSONB and no meaningful relational structure at all, are close to equivalent; PostgreSQL with JSONB still edges ahead if the catalog needs to join to inventory, pricing, or supplier tables elsewhere in the same system, which most real catalogs eventually do.
ML model metadata (hyperparameters, evaluation metrics that vary by model type, training lineage). This looks equally flexible-schema at first glance, hyperparameters and metrics genuinely vary by model type, but it is actually a strong case FOR PostgreSQL, not against it, because the metadata almost never stands alone: it needs to join back to a dataset table, an experiment table, and a user or team table, and the single most important operation on this data, atomically flipping which model version is flagged "production" while un-flagging the previous one, is a transactional, joined, all-or-nothing operation by nature. Storing the variable hyperparameter and metric fields in a JSONB column on an otherwise normal, foreign-keyed model_versions table gets the schema flexibility this scenario needs while keeping the transactional swap and the joins to dataset and experiment tables fully native.
Worked example
The concrete case for choosing between PostgreSQL and MongoDB rarely comes down to which one can store flexible data (both can); it comes down to what the actual query and transaction pattern costs on each. Frame the "production model swap" operation from the ML-metadata scenario explicitly as SQL to make the transactional requirement concrete:
-- atomic production-model swap, the transactional
-- operation that makes this a PostgreSQL-favoring scenario despite the flexible metadata.
BEGIN;
UPDATE model_versions
SET is_production = false
WHERE model_id = 'checkout-fraud-classifier'
AND is_production = true;
UPDATE model_versions
SET is_production = true
WHERE model_id = 'checkout-fraud-classifier'
AND version = 'v14';
-- hyperparameters and metrics live in a JSONB column on the same row:
-- metadata @> '{"framework": "xgboost"}' -- containment query, uses a GIN index
-- metadata -> 'eval_metrics' ->> 'auc' -- path extraction for a single metric
COMMIT;
Both updates inside this single transaction succeed together or fail together, so it is never possible for two model versions (or zero) to be simultaneously flagged production, a correctness property this scenario genuinely needs. The commented containment and path-extraction queries show the JSONB column answering the "flexible metadata" half of the requirement in the same table, with the same transaction boundary, and the same standard SQL connection any BI or migration tool already speaks.
Trade-offs & pitfalls
- Treating "MongoDB doesn't support transactions" as still true. It has since version 4.0 (single-shard) and 4.2 (across shards); the real, current gap is relative cost and capability versus PostgreSQL's native transactional model, not existence.
- Assuming a flexible-schema scenario automatically favors a document database. The ML-metadata scenario looks flexible-schema on the surface and is actually a strong relational case, once the join and atomic-swap requirements are considered; check the actual operations the data needs, not just its shape.
- Leaving a MongoDB collection's schema completely unvalidated "because it's flexible." Without a validator, schema drift accumulates silently across different code paths and surfaces later as a confusing application bug, not a database error.
- Over-normalizing the JSONB fields into rigid columns "for consistency." That defeats the reason to use JSONB in the first place; keep genuinely dynamic, sparse, or per-category-varying fields in the JSONB column and normalize only what is truly common and stable across every row.
- Indexing a JSONB column generically without checking the actual query pattern. A GIN index tuned for containment queries does not necessarily serve path-based extraction queries efficiently; match the index configuration to how the application actually queries the column.
Explain polyglot persistence: when it is valuable, common architecture patterns that combine multiple data stores, and the operational and developer pitfalls to avoid. Then sketch a minimal architecture for a product that needs transactional order writes, flexible per-user profile data, and fast product-lookup search: which store would you put each responsibility in, and why?
Sample Answer
Direct answer
Polyglot persistence means deliberately using different data stores for different parts of one system, each chosen for the access pattern it actually serves, rather than forcing a single database to be good at everything. It earns its complexity when a system has genuinely different workloads coexisting, a transactional write path alongside a search path alongside a flexible-schema read path, exactly the shape in this question, and it is overreach when adopted reflexively for a system whose workloads are actually similar enough that one well-run database would have handled all of them.
Structured elaboration
When it is valuable. Distinct access patterns with genuinely different optimal storage shapes coexisting in one product: transactional writes needing atomicity, consistency, isolation, and durability (ACID) for orders and payments; free-text or faceted search needing an inverted index for product search; flexible per-entity documents needing schema freedom for user profiles with varying optional fields. Serving all three from one relational database usually means either a mediocre search implementation bolted onto SQL, or forcing profile data into a rigid schema that fights its natural shape.
Common architecture patterns. A system of record plus derived read models, where one store owns the truth and others are kept in sync as read-optimized projections via change data capture (CDC) or an outbox pattern (writing the event to an outbox table in the same transaction as the actual data change, so a separate process can publish it reliably afterward instead of risking the change and the notification getting out of sync), is the dominant, safest pattern because it keeps a single, unambiguous source of truth. Split ownership by bounded context, where each service genuinely owns and is the sole writer of its own store, and other services reach it only through that service's API, never by reading its database directly, is the complementary organizational pattern.
Operational and developer pitfalls to avoid. Multiple sources of truth for the same fact, for example both an order service and a search index both treating themselves as authoritative for "is this in stock," which drifts apart over time; always designate exactly one owner per fact. Synchronization lag surprising a caller that expects same-store consistency it does not actually have; design explicitly for which paths tolerate propagation delay and which cannot. Operational sprawl, where N stores means N backup strategies, N monitoring setups, and N sets of on-call runbooks and access controls to maintain correctly, a real, recurring cost that should be weighed against the workload-fit benefit, not assumed free. Treating cross-store atomicity as routine, since there is no shared transaction manager spanning, say, a relational database and a search index, so the architecture must be built around synchronization that is eventual (the two stores agree after a short delay, not instantly), idempotent (applying the same update twice has the same effect as applying it once, so a duplicate message causes no harm), and replayable (past events can be reprocessed from history to rebuild or repair a store) rather than an illusion of atomic writes across stores.
Worked example
flowchart LR
Client -->|checkout| OrderSvc[Order service]
Client -->|profile edit| ProfileSvc[Profile service]
Client -->|search| SearchSvc[Search service]
OrderSvc -->|ACID writes| OrdersDB[(Relational DB: orders)]
ProfileSvc -->|flexible per-user documents| ProfileDB[(Document store: profiles)]
ProductSvc[Product service] -->|source of truth| ProductDB[(Relational DB: products)]
ProductDB -->|CDC or outbox| SearchIndex[(Search index: product lookup)]
SearchSvc -->|query| SearchIndex
Transactional order writes go to a relational database, ACID across order lines, payment status, and stock decrement in one commit. Flexible per-user profile data goes to a document store, each user's profile a self-contained record with optional fields that vary per user, fetched whole by identifier, with no cross-user joins needed. Fast product-lookup search goes to a dedicated search index, fed by CDC or an outbox from the product service's own relational store of record, because free-text and faceted search is exactly what an inverted-index engine is built for and a basic relational text match is not.
Trade-offs and pitfalls
Running three stores for a system this size is only worth it once product search genuinely needs facets, free text, and ranking beyond a few relational indexes, and profile data genuinely varies enough per user that a rigid schema would fight it. A smaller version of this same product, few users, simple structured profile fields, simple catalog search, is better served by one relational database with good indexing, and splitting into three stores too early is the overreach pitfall materializing in practice.
What would flip the recommendation: at a small enough scale, collapse profile and search into the same relational database as orders, profiles as a nullable-column or JSONB-augmented table, search via a basic full-text index, until a measured need, search relevance complaints, or profile schema churn causing frequent migrations, actually justifies splitting out a dedicated store.
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.