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 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.
Compare using a managed time-series database versus an in-memory cache for ingesting and querying high-frequency telemetry that also requires short-term analytics. Which combination provides best latency and query flexibility, and what architecture would you propose?
Sample Answer
Direct answer
Don't choose between a managed time-series database (TSDB) and an in-memory cache for high-frequency telemetry: use both, in a layered architecture, because they solve different halves of the requirement. The cache (Redis or similar) serves the most recent data point per series with sub-millisecond latency for dashboards and alerting, and the TSDB durably stores the full-resolution history and serves the short-term analytical queries (trends, aggregations over the last hour or day) that a cache was never designed to answer well.
Why neither one alone is enough
An in-memory cache alone is excellent at "what is the latest value for this sensor," but has no native concept of a time series: computing "the average over the last 15 minutes" means the application reading back a window of raw values and aggregating them itself, and a cache-only design either has to hold significant history in memory (expensive, and gone on restart unless persistence is configured) or push that history somewhere else anyway. A managed TSDB alone is built for exactly that history-and-aggregation problem, but even a well-tuned one adds latency for the single most common telemetry query (the current value), because it's optimized for range and aggregate queries, not point lookups on the newest row.
Proposed architecture
| Component | Role |
|---|---|
| Ingest path | Telemetry writes go to both the cache (as the latest-value key per series, e.g. SET sensor:{id}:latest) and the TSDB (as a durable, time-ordered point), either directly or via a small fan-out step so a single write call updates both |
| Cache (Redis) | Serves "current value" and "last N points" style queries (using a bounded list or a small time-window structure) for dashboards and real-time alerting; sub-millisecond latency, no aggregation logic beyond what's cheap to compute on a small in-memory window |
| Managed TSDB | System of record for full-resolution history; serves short-term analytical queries (rolling averages, percentiles, trend detection over the last hour/day) and any query that needs more history than the cache is holding |
| Retention/downsampling | The TSDB downsamples older data (raw resolution kept for a short window, aggregated rollups kept longer) to control storage growth, which the cache never needs to worry about since it only ever holds recent data |
This is the same latency-versus-query-flexibility trade-off that shows up across database selection generally: the cache buys latency by deliberately supporting fewer query shapes, and the TSDB buys query flexibility by accepting higher latency than an in-memory lookup.
What this gets right, and where it can go wrong
The combination gives the best of both stated requirements (latency and query flexibility) precisely because neither system is asked to do the other's job: alerting and live dashboards read the cache and never touch the TSDB's query planner, while trend analysis and reporting read the TSDB and never contend with the cache's memory budget. The risk this design introduces is consistency between the two: if the fan-out write to the cache succeeds but the TSDB write fails (or vice versa), the "latest value" and "historical record" can briefly disagree. For most telemetry use cases that's an acceptable trade (a dashboard being a few seconds stale during a rare write failure is far less costly than adding synchronous coordination between the two writes), but it should be a deliberate decision, with monitoring on write failures to either side, not an unexamined gap.
Trade-offs and pitfalls
- Don't let the cache become an unintentional second system of record. If the cache is configured to persist and hold significant history, the team now has two places storing overlapping data with two different consistency and durability models, without having decided that on purpose.
- Downsampling policy needs to be decided before storage costs become a problem, not after. High-frequency telemetry at full resolution grows fast; deciding how long raw-resolution data is kept versus rolled up is part of the architecture, not an afterthought.
- A dual-write (cache and TSDB) without a plan for partial failure will eventually produce a real inconsistency. Decide explicitly what happens if one write succeeds and the other doesn't (retry, alert, accept and reconcile later), rather than assuming it won't happen.
- If the workload's real requirement turns out to be complex real-time aggregation (not just "latest value" and "recent trend"), a stream-processing layer (Kafka Streams/Flink) in front of both stores may be a better fit than pushing that logic into either the cache or the TSDB directly.
You must pick a primary datastore for a payments system requiring strict transactional consistency, fraud detection analytics, and monthly reconciliation reports. Propose an architecture that may include more than one data platform, explain data flow between components, and justify choices based on consistency, latency, and analytics needs.
Sample Answer
Direct answer
For a payments system, split the workload across two purpose-built platforms and connect them with a change stream, rather than forcing one database to be good at everything. Use a strongly consistent relational database (or a distributed SQL system like Google Cloud Spanner) as the single system of record for the money-moving path, stream every committed change out via change data capture (CDC, a mechanism that reads a database's internal transaction log and turns each row change into an event), and land that stream in a columnar analytics warehouse for fraud scoring and monthly reconciliation. The OLTP database (online transaction processing: a system optimized for many small, concurrent reads/writes with strict correctness) never talks directly to the analytics side in the request path, so a slow fraud query or a big reconciliation scan can never add latency to a customer's payment.
Architecture and data flow
Component 1: system of record (OLTP). A relational database (PostgreSQL/MySQL-compatible, or a managed option like Amazon Aurora or Cloud Spanner) holds accounts, ledger entries, and transaction state. Every payment is a single ACID transaction (atomicity, consistency, isolation, durability: the guarantee that a transaction either fully applies or not at all, leaves data valid, is isolated from concurrent transactions, and survives a crash once committed), run at SERIALIZABLE or the engine's strictest practical isolation level, so two concurrent debits against the same balance can never both succeed and double-spend the account. This is the only place writes to money happen.
Component 2: change stream. A CDC connector (Debezium is the common open-source choice) tails the OLTP database's write-ahead log and publishes one event per committed row change onto a durable log such as Kafka. This decouples "the transaction committed" from "everyone who needs to know about it finds out," so downstream consumers can be slow, restarted, or temporarily down without blocking payments.
Component 3: real-time fraud scoring. A stream processor (Kafka Streams or Flink) consumes the change stream, joins it against recent history and device/session signals, and scores each transaction. High-risk transactions write a hold flag back to the OLTP system through the normal transactional API, idempotently keyed by transaction ID so a retried or duplicated event cannot apply the same hold twice.
Component 4: analytics and reconciliation. The same change stream is sinked into a columnar warehouse (Snowflake, BigQuery, or Redshift). Monthly reconciliation jobs run here: compare internal ledger totals against external bank/processor settlement files, using checksums and row counts per batch to prove nothing was lost or double-counted in transit. This workload can run full-table scans and heavy joins without any risk to the OLTP system, because it reads from a copy, not the source.
flowchart LR
Client[Payment client] --> API[Payment API service]
API -->|write ledger row, serializable txn| OLTP[(Relational OLTP\nsystem of record)]
OLTP -->|CDC stream| Bus[[Kafka change stream]]
Bus --> Fraud[Stream fraud scorer]
Fraud -->|hold flag, idempotent write-back| OLTP
Bus --> WH[(Columnar warehouse\nreconciliation and analytics)]
Bus --> Audit[(Append-only audit log)]
Worked example: why single-platform doesn't fit
Say the service processes 500 transactions per second (TPS) at peak, and a monthly reconciliation job needs to scan 90 days of transaction history (roughly 500 * 86,400 * 90 ≈ 3.9 billion rows) and join it against a settlement file. Running that scan directly against the OLTP primary would compete for the same buffer pool (the in-memory area where the database engine caches recently used data pages so it doesn't have to re-read them from disk) and lock manager that the live payment path depends on; even a well-indexed OLAP-style (online analytical processing: the counterpart to OLTP, large scans and aggregations for reporting rather than many small transactional writes) query with a large sort or hash join can hold shared resources long enough to add tail latency to concurrent writes. Separating the two means the OLTP database is sized and tuned purely for point lookups and small transactional writes (small working set, aggressive caching, low lock contention), while the warehouse is sized purely for sequential scans and columnar compression over the same 3.9 billion rows, with no shared contention between them.
Trade-offs and pitfalls
- Consistency boundary matters. The fraud-hold write-back has to be idempotent and the CDC pipeline has to guarantee at-least-once delivery with a de-duplication key downstream, or a redelivered event could double-apply a hold or a reversal. "Exactly-once" in practice means at-least-once delivery plus an idempotent consumer, not a magic delivery guarantee.
- Operational cost. This design adds CDC, a message bus, a stream processor, and a warehouse: four extra systems to monitor, upgrade, and page on. That overhead is justified here because payments cannot tolerate the alternative (a single database straining to be both a fast ledger and a fraud/analytics engine), but it would be over-engineering for a system without the same consistency and scale pressure.
- Reconciliation needs a proof, not just a copy. A common mistake is treating the warehouse copy as automatically correct. Reconciliation should independently verify completeness (row counts, checksums, watermarking on the CDC stream) rather than assuming replication never drops or duplicates an event.
- **A single globally-consistent NewSQL system (NewSQL: a class of databases that aim to keep relational ACID guarantees while scaling out like a distributed system, e.g. Spanner or CockroachDB) can replace the OLTP component if the team wants one fewer moving part for the transactional side, but it does not remove the need for a separate analytics store: OLAP-shaped queries still shouldn't run against the transactional cluster.
When should a customer choose a managed database service versus self-managing databases on VMs or on-prem? Discuss tradeoffs across operational burden, total cost of ownership, customizability, compliance and auditability, upgrade control, and vendor lock-in. Provide decision criteria for a heavily regulated financial firm.
Sample Answer
Direct answer
For a heavily regulated financial firm, default to a managed database service from a provider holding the specific compliance certifications the regulator actually requires, for example SOC 2 Type II (an independently audited report confirming a provider's security controls held up over a period of months, not just on the day of a single check), PCI DSS (the Payment Card Industry Data Security Standard, the required control set for anyone storing or processing card payment data) for payment data, and any jurisdiction-specific attestations. Matching a large provider's patching cadence, tested backups, and audit tooling in-house is a cost few firms should choose to carry. Self-hosting only earns its keep when a specific, NAMED constraint forces it: a data-residency rule the provider cannot satisfy in-region, a mandated on-premises boundary, or a genuinely required customization blocked by the managed offering's extension allowlist.
Structured elaboration
Operational burden. Managed services absorb patching, backup execution, and failover mechanics. Self-hosting puts all of that on the firm's own team, and in a regulated environment that work itself becomes something the firm must prove happened on schedule, patches applied, backups actually tested, access controlled, which is strictly more work than performing the operations alone.
Total cost of ownership. Instance or license cost is usually the smaller piece; staffing, around-the-clock on-call coverage, security engineering, audit-evidence collection, dominates at real scale. A regulated firm pays for a compliance function regardless of hosting model, so self-hosting does not remove that cost, it adds the operational cost a managed service would otherwise have absorbed on top of it.
Customizability. This is the strongest genuine case for self-hosting. If the workload needs a storage engine, extension, or kernel-level tuning a managed offering's allowlist truly does not support, self-hosting is the only path. Verify the actual allowlist of the specific offering being evaluated first, because many assumed gaps turn out to be covered once checked, major managed PostgreSQL offerings, for instance, support extensions such as PostGIS (adds geographic and spatial data types and queries) and pg_cron (runs scheduled jobs inside the database itself), and increasingly let teams register their own sandboxed, trusted extensions.
Compliance and auditability. This cuts both ways, and it is the crux of "heavily regulated." A managed provider ships a shared-responsibility model with independently audited controls for the infrastructure layer, physical security, hypervisor isolation, patching SLAs, that a firm would otherwise have to build and prove itself. What the firm still owns regardless of hosting model is access control, data classification, encryption key management, many managed offerings support customer-managed keys, and query-level audit logging. Self-hosting does not remove these obligations; it just removes the second party who is also independently accountable for the infrastructure half.
Upgrade control. Self-hosting lets a firm pin an engine version indefinitely, relevant if a regulator requires documented change-control sign-off before any upgrade. Managed services generally enforce a maximum supported-version window and can push an upgrade on the provider's own timeline, which some regulated environments genuinely cannot accept without a formal exception process. This is a real, specific reason a firm might self-host one particular workload while running everything else managed.
Vendor lock-in. A managed offering of an open, widely implemented engine, managed PostgreSQL or MySQL, keeps the firm able to migrate to another provider or self-host later with a dump and restore plus a connection-string change. A proprietary, managed-only engine with no open equivalent makes that exit materially harder, which matters more for a regulated firm that may face a regulator-mandated provider change on a timeline it does not control. Mitigate by preferring managed offerings of open engines where the workload allows it, and by pricing lock-in risk into the decision from the start, not discovering it after committing.
Worked example
The firm's core ledger, subject to the heaviest audit scrutiny, is a strong candidate for managed PostgreSQL, or a similarly open, widely audited managed engine, from a provider holding the required certifications, with customer-managed encryption keys and query-level audit logging enabled, because none of the named regulatory concerns, residency, a truly unsupported customization, a change-control-incompatible upgrade cadence, apply to a standard ledger workload. A separate workload with a genuine on-premises data-residency boundary the provider cannot satisfy in-region is the one piece that goes self-hosted, decided workload by workload rather than as a single all-or-nothing policy.
Trade-offs and pitfalls
A pitfall is treating "regulated industry" as an automatic vote for self-hosting. In practice it more often argues for managed, because the provider's independently audited controls reduce what the firm itself must prove, while self-hosting concentrates the entire audit burden internally without necessarily buying more actual security.
A second pitfall is assuming a specific extension or customization gap exists without checking the current allowlist of the specific offering being evaluated. These change frequently, and an outdated assumption can drive an unnecessary, expensive self-hosting decision.
What would push the recommendation further toward self-hosted: a genuine, named, unwaivable regulatory requirement, verified against the actual regulation text rather than a general impression of risk. That is the one class of reason strong enough to accept the operational and audit burden self-hosting adds.
Explain the difference between a key-value store and a document store. For a session store (user login sessions with expiry) and a product-catalog with nested attributes, which store would you choose for each and why? Mention indexing and query implications.
Sample Answer
Direct answer
A key-value (KV) store maps one opaque key to one opaque value: the engine has no idea what is inside the value, so it cannot query or index into it. A document store maps a key to a structured, typically JSON, document whose internal fields the engine CAN see, index, and query. A login session, read and written whole by session id and never queried by its internal fields, fits a key-value store. A product catalog with nested attributes (color, size, a spec sheet, a list of variants), which shoppers filter and sort BY, needs a document store's ability to index and query inside that structure.
Structured elaboration
The core distinction. Both kinds of store answer "get by key" in roughly constant time. The difference is what happens after that: a KV store treats the value as opaque bytes, with no query language and no awareness of structure inside it. A document store additionally indexes and queries fields INSIDE the document, for example WHERE variants[].size = 'M', at the cost of the engine having to parse and index document structure on every write.
Session store: key-value. A session record is always read and written whole, by session id; nothing in the hot path ever needs to ask "find all sessions where role = admin." Add expiry (a TTL, or time-to-live, an attribute or command telling the store when to remove the record automatically) and this is exactly what a KV store like Redis or DynamoDB is built for. Indexing and query implications: none beyond the primary key, which is precisely why a document store's indexing machinery buys nothing here.
Product catalog: document store. Shoppers filter and sort by nested attributes constantly, and a product record is naturally nested (a product has variants, each variant has its own attributes). A document store's multikey and array indexes let it answer "products where any variant has size = M and color = blue" directly. Forcing this into a pure KV store means either flattening every filterable attribute into the key (unworkable past one or two filter dimensions) or exporting to a separate search index just to answer catalog-browse queries, which is the extra system avoided entirely if the store already chosen can index nested fields.
Why this distinction is worth making to a non-technical stakeholder. Paying for indexing power nobody uses is paying for a feature nobody asked for. Conversely, saving money by putting genuinely filterable, browsable data into a plain lookup table means engineering will need to bolt on a second system later to support "let customers filter by color," which costs more over time than choosing correctly up front. The database choice here is really a bet on what the business will ask users to DO with the data: look it up by a known key, or search and filter it.
Worked example
Session store: SET session:<id> <blob> EX 1800 (Redis, a 30-minute expiry) or a DynamoDB item with a TTL attribute, a single get-by-id read path, and no secondary index ever created for it. Product catalog: a document shaped like
{ "sku": "SHIRT-42", "variants": [
{"size": "M", "color": "blue", "price": 24.99, "stock": 12},
{"size": "L", "color": "blue", "price": 24.99, "stock": 3}
]}
with a compound multikey index on variants.size and variants.color, supporting a query like "find products where a variant has size M and color blue" directly against the index.
Trade-offs & pitfalls
The common mistake is picking a document store "to be safe" for something that is really pure key-value access (session data, feature flags, rate-limit counters), paying indexing and storage overhead for structure nobody queries. The opposite mistake, picking a KV store for genuinely queryable data and discovering months later that an internal field needs filtering, is the more expensive one to unwind, since it usually means a live data migration under production load.
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.