Skip to content
Tech Interview Prep
Technical interview guide

NoSQL, Graph & Key-Value Data Stores

When a relational database isn't the right fit: document, key-value, graph, and vector stores, and how to choose between them.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain what NoSQL means and why the term is not very useful.

Answer

"NoSQL" is a 2009-era label for stores that dropped the relational model. It survives as a convenient negation, not as a description. A Redis instance and Neo4j share exactly one property: neither is Postgres. Everything an interviewer actually cares about (data model, query shape, consistency, failure mode) is decided by which family you picked, and the label hides that.

What the families do share is the shape of the trade: give up generality (joins, ad-hoc queries, multi-row transactions, strong consistency) to buy something specific.

familyexamplesqueryable bywhat you give up
key-valueRedis, DynamoDBthe key, nothing elsequerying by value; Redis keeps data in RAM
documentMongoDB, Couchbaseany indexed field in the documentjoins; MongoDB caps a document at 16 MB
wide-columnCassandra, HBasethe partition key, then clustering columnsany query that doesn't name the partition key
graphNeo4j, Neptunetraversal from a start nodecheap full-graph aggregation

What breaks. Four failure modes the choice invites, and how you'd catch each.

Eventual consistency surprises. DynamoDB reads are eventually consistent by default, so a read issued right after a write can miss it; strongly consistent reads exist and cost 2x the RCU. Cassandra's consistency is per query (ONE, QUORUM, ALL), so a QUORUM write followed by a ONE read can return the old value. Catch it with read-your-writes assertions in integration tests: production dashboards won't show it.

Hot partitions. DynamoDB caps a single partition at 3,000 RCU / 1,000 WCU, so one popular partition key throttles while the table's overall capacity sits idle. Cassandra's version is a partition that outgrows its node; the common rule of thumb is to keep partitions under ~100 MB. Catch it in DynamoDB's ThrottledRequests and per-key consumed capacity, and in Cassandra's nodetool tpstats and coordinator timeouts.

Unbounded queries. Cassandra's ALLOW FILTERING, DynamoDB's Scan, and an unindexed MongoDB find all read everything. They pass in dev at 10k rows and take the cluster down at 100M. Catch them in slow-query logs and MongoDB's profiler.

Schema drift. Document stores don't enforce a schema, so two documents in one collection diverge and the code reading field X breaks on the one written by an older service version. MongoDB's $jsonSchema validator (3.2+) is the fix, and it's opt-in. Catch it with a sampling job, or in production.

The trade has narrowed. Postgres has had JSONB with GIN indexes since 9.4; MySQL's JSON type since 5.7. Distributed SQL (CockroachDB, Spanner) shards and keeps serializable transactions. "Relational can't do JSON" and "relational can't scale" were fair in 2010; both need re-checking now.

So the framing isn't "SQL or NoSQL," it's "what does this workload need that my default can't give?" That forces a specific gap to be named, and often the honest answer is that there isn't one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

What does 'schemaless' actually mean, and what does it cost?

Answer

It means the database does not enforce a schema. It does not mean there is no schema: application code that reads a document expects particular fields with particular types and meanings, and that expectation is a schema whether or not anything checks it.

So what is actually removed is enforcement and visibility. The consequences follow from both.

Drift becomes invisible. Documents written by different code versions accumulate in the same collection. A field renamed in version 3 leaves version 2's documents with the old name forever, and nothing lists which shapes exist. Six months later, nobody can answer 'what fields does this collection have' without scanning it and sampling.

Every reader must be defensive. Since any document might predate any change, readers handle missing fields, old names, and changed types: that defensive code multiplies across every consumer, and one that forgets fails at runtime on old data, typically for a specific old record rather than reproducibly.

Nothing catches a typo. Writing emial creates a new field silently. In a relational database that is an error at write time; here it is a corrupted record discovered when something downstream comes up empty.

Migrations do not disappear: they become implicit and permanent. Instead of one migration that transforms all rows, you have handling code for the old shape, in every reader, forever. The work was not removed; it was distributed and made ongoing.

What I would do about it. Use the schema validation features these stores offer: they exist precisely because unenforced schemas proved painful. Version documents explicitly with a schema version field, so readers can dispatch on it rather than guess from shape. Run genuine migrations when a shape changes, rather than accumulating compatibility handling. And keep the expected shape in one validated place in code, a parsing layer at the boundary, rather than scattered field access throughout.

Done that way, a document store is workable. What does not work is treating 'schemaless' as meaning the problem has gone away.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Explain eventual consistency and how it affects application design.

Answer

The 90-second answer. Eventual consistency is a liveness guarantee: if writes stop, every replica converges to the same value. It says nothing about when. Between the write and convergence a read can return any value that replica has seen: usually the previous one, but not necessarily in order. The design consequence is that the application, not the store, owns the staleness window: you decide which reads must observe the latest write and pay for it, and which can tolerate a replica that is behind.

What the defaults actually are. Most designs go wrong here, because the default is usually the weak one.

SystemDefaultWhat strong costs
DynamoDBEventually consistent reads2× RCU: 1 RCU per 4 KB strongly consistent vs 0.5 eventually consistent
CassandraCL ONE for reads and writesR + W > RF; QUORUM on both sides at RF=3
MongoDBreadConcern local, writeConcern majority (5.0+)causal consistency sessions
Cosmos DBsessionbounded staleness (K versions or T seconds), or strong
Spanner—TrueTime commit-wait, ~7 ms average in the OSDI 2012 paper

S3 is the counterexample: since December 2020 it gives strong read-after-write consistency for all operations, because at that scale the trade stopped being worth making.

Failure modes, and how you see them.

Read-your-writes. A user saves a profile; the next read hits a replica behind by the replication lag, shows the old value, and they save again. Detect it with a canary that writes a unique token and reads it back through the same path, alerting on the miss fraction. On Postgres the lag itself is in pg_stat_replication (replay_lag); on Cassandra, in hinted-handoff and read-repair metrics.

Monotonic reads. Two reads land on different replicas and the value goes present → absent → present. Same canary, read twice.

Concurrent writes. Something must pick a winner. DynamoDB Global Tables and Cassandra both default to last-write-wins, which silently drops one write. Fine for a presence flag, wrong for a cart. Cassandra's hinted handoff only covers a node that is down for up to max_hint_window_in_ms, 3 hours by default; past that the write is gone unless a repair runs.

Design responses, in the order I would reach for them.

  1. Return the written value from the write response instead of re-reading. This removes the read-your-writes problem entirely for the common save-then-display flow.
  2. Session stickiness or a session token. Cosmos DB session consistency and MongoDB causal consistency sessions both give read-your-writes and monotonic reads within a session, and both are the sensible default for user-facing traffic.
  3. Route the specific read to the leader. A balance check before a withdrawal, an inventory decrement: a handful of operations, not a whole service.
  4. Make writes idempotent and commutative. counter += 1 merges; counter = 42 does not. A CRDT counter or a set union converges without a coordinator.
  5. Show the staleness. "Last updated 4s ago" beats presenting a stale number as current.

The framing. Eventual consistency is a trade for availability and latency, not a defect. The interview answer is to name which operations need strong consistency, usually far fewer than the first pass suggests, and to say what each one costs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do you handle the loss of foreign keys in a store that has none?

Answer

You cannot fully replace it, and being honest about that shapes the design.

A foreign key guarantees a reference points at something real, for every writer, atomically. Without it, dangling references will occur (through races, partial failures, out-of-order deletes, and bugs) and the design must tolerate them rather than assume they cannot happen.

So the first move is making readers tolerant. Code fetching a referenced entity must handle absence: render a placeholder, skip the item, or fail gracefully. Code that assumes presence will crash on production data eventually, and usually on one record rather than reproducibly.

Model to reduce references. If related data is always accessed together, bounded, and exclusively owned, embedding removes the reference entirely and the problem with it. That is often available and often overlooked.

Handle deletion deliberately. Options are cascading in application code, which is not atomic and can fail partway, leaving a half-deleted graph; soft deletion, so the referenced item still exists and readers see it as deleted; or refusing deletion while references exist, which requires a scan or a maintained reference count.

Soft deletion is usually the most robust here, precisely because it sidesteps the atomicity problem: nothing disappears, so nothing dangles.

Detect what leaks through. A scheduled integrity check scanning for dangling references, reporting rather than silently repairing, converts an invisible problem into a visible one. Without it, corruption accumulates unnoticed, and this check is the piece teams most often skip.

Make writes idempotent and ordered where possible, so a retry cannot create a reference to something that was never created.

What I would resist is a validation layer claiming to enforce referential integrity in application code. It cannot: two concurrent operations can both validate successfully and produce an inconsistent result, because there is no atomicity across the check and the write. Claiming enforcement that does not exist is worse than acknowledging the gap, because downstream code will then be written to assume it.

And if references and integrity are central to the domain, that is genuine evidence the store choice deserves revisiting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do you decide whether to embed or reference in a document model?

Answer

Three questions decide it: are these always accessed together, is the child bounded in size, and is it owned exclusively by this parent?

Embed when all three are yes. Order lines within an order: always fetched with the order, bounded by how much someone buys, meaningless outside it. One read gets everything and the write is atomic at the document level, which is a real guarantee worth having.

Reference when any is no. Comments on a post are unbounded. A customer referenced by many orders is shared. A user's activity log is accessed independently and grows forever.

The two failure modes are symmetric and both common.

Over-embedding an unbounded array eventually hits the document size limit, but the practical damage arrives long before that, because every read of the parent transfers the entire array. A post with 40,000 comments becomes slow to fetch even when you only wanted the title. And writes rewrite the whole document, so contention on the parent grows with the child count.

Over-referencing recreates relational joins in application code, without the database's ability to optimise them. Fetching a document, extracting ids, issuing another query, stitching results: that is a join, executed badly. At that point the honest conclusion is usually that a relational database was the better fit.

The hybrid that often works is embedding a bounded subset alongside a reference: the five most recent comments embedded for display, with the full set referenced. It costs a denormalisation you must maintain, so it needs the usual obligation: a stated mechanism keeping it current.

And the question I would ask before any of this: does this data actually vary per record? If the shape is fixed and known, the modelling decision may be a symptom of a store choice worth revisiting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Explain how wide-column data modelling works and why it inverts relational practice.

Answer

In a wide-column store like Cassandra, data is partitioned by a partition key and sorted within the partition by clustering columns. A query that does not specify the partition key is either rejected or becomes a scatter-gather across every node, so the partition key is not an optimisation, it is a precondition for querying at all.

That single constraint inverts the design method. Relational modelling defines entities, normalises them, and lets the query planner work out how to answer whatever you ask. Wide-column modelling starts from the queries: enumerate them, then create a table per query, shaped so each is a single-partition read. The same data is written to several tables.

So denormalisation is not a compromise here: it is the design. Writes are cheap and expected to fan out; reads must be single-partition. This is coherent, but it demands that access patterns be known before modelling, which is a strong requirement.

The partition key carries two more requirements. It must distribute evenly, or one node takes disproportionate traffic and caps the cluster regardless of how many nodes you add. And partitions must stay bounded: everything keyed by one tenant grows without limit and eventually becomes unmanageable, so a high-volume key usually needs a compound partition key (tenant plus month, say) to keep partitions a workable size.

The cost of being wrong is high. A new query pattern means a new table and a backfill of all existing data, which is a project rather than a migration. That rigidity is the real trade being made, and it is why this suits workloads whose access patterns are well understood and stable (time series, event logs, messaging) and suits exploratory or evolving products badly.

The corollary worth stating: if you cannot enumerate your queries confidently, this is the wrong model, because the design method has nothing to start from.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What is a hot partition and how would you design around one?

Answer

A hot partition is one receiving disproportionate traffic. Since a partition lives on one node, its throughput is capped by that node, so adding capacity to the cluster does not help, and the symptom is throttling or high latency on specific keys while overall utilisation looks fine. That mismatch between aggregate and per-key metrics is what makes it confusing to diagnose.

The causes are recognisable:

Monotonic keys. Partitioning by timestamp or sequence sends every write to the newest partition, so writes never spread regardless of how many nodes exist.

Natural skew. Tenant identifiers where one customer is a thousand times larger than the median; celebrity accounts in a social product; a popular product in a catalogue.

Unbounded partitions. A key whose partition grows forever, all events for one tenant, becomes both hot and unmanageably large.

The remedies:

Add entropy to the key. Append a suffix, a hash bucket or a random value in a small range, so writes spread across several sub-partitions. The cost is that reads must query all of them and merge, so the fan-out factor is a deliberate trade, chosen from measured skew rather than guessed.

Use a compound key. Tenant plus month keeps partitions bounded and spreads them, and is usually better than random suffixes because reads for a known period still hit one partition.

Separate the outliers. If one tenant is genuinely enormous, giving them a different key strategy (or their own table, or their own cluster) is legitimate. Designing one scheme for both the median and a thousand-times outlier compromises both.

Cache in front. A hot read partition is often best addressed by a cache, since the traffic is concentrated precisely because the data is popular, which is exactly when caching works.

What matters most in practice is detecting it. Aggregate metrics hide it entirely, so I would want per-partition or per-key throttling metrics, and I would test with realistically skewed data: uniformly generated test data has no skew and will never reveal the problem before production does.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How do you size partitions and choose partition-key cardinality so a table stays within per-partition item and throughput limits?

Answer

Two limits decide the design: how much data one partition key value can hold, and how much throughput one partition can absorb. Both DynamoDB and Cassandra hash the partition key to place data, so cardinality and per-key volume are the levers.

DynamoDB. All items sharing a partition key form an item collection, capped at 10 GB. Max item size is 400 KB. A single partition supports up to 3,000 RCU or 1,000 WCU; adaptive capacity can lend unused capacity to a hot partition but does not remove the ceiling. The partition key needs enough distinct values to spread load, and no single value may accumulate unbounded items.

Cassandra. The partition is the unit stored and replicated on a node. Guidance is to keep partitions under 100 MB, ideally under 10 MB, and under 100,000 rows. Wide partitions cause GC pressure, slow reads, and expensive repair and compaction.

Worked example: IoT sensor readings. Table: PK = sensor_id, SK = timestamp. One reading per second, 200 bytes each.

  • Per day: 86,400 × 200 B = 17.28 MB
  • Per year: 17.28 MB × 365 ≈ 6.3 GB
  • Crosses DynamoDB's 10 GB item collection limit in ~1.6 years

Fix: PK = sensor_id#YYYY-MM-DD. Each partition holds one day, ~17 MB and 86,400 rows: under both the 10 GB and the 100k-row guidance. Throughput is 1 write/sec = 1 WCU, far under 1,000 WCU. If a sensor produced 5,000 writes/sec of 1 KB, that is 5,000 WCU on one partition, so you would add a random suffix (sensor_id#bucket#shard) and accept scatter-gather reads.

DynamoDBCassandra
Partition unititem collection (same PK)partition
Size limit10 GB per item collection<100 MB, ideally <10 MB
Row/item limit400 KB per item<100k rows
Throughput per partition3,000 RCU / 1,000 WCUnode-bound, watch p99

Failure modes. Low-cardinality keys (status, country, tenant tier) concentrate load; a celebrity user does the same. Detect with CloudWatch ThrottledRequests and ConsumedWriteCapacity, or Cassandra dropped mutations and p99 read latency. Mitigate by sharding writes, but that turns a point read into a scatter-gather.

Trade-off. More partitions mean more read fan-out and overhead; fewer mean hot spots. Choose the coarsest key that keeps each partition under the size and throughput ceilings for the retention window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you design a DynamoDB table for a known set of access patterns?

Answer

First 60–120 seconds

Clarify two things: are the access patterns fixed for the next 6–12 months, and what are the item sizes and read/write ratio? Then the answer: in DynamoDB the keys are the design, so I write down every access pattern with what is known at query time and what must come back, and choose keys so each one is a single GetItem or a single Query against one partition. Anything that can't be expressed that way gets a secondary index or a duplicated item. Assumptions: patterns known, items under 400 KB, on-demand billing.

Worked example: an orders service

#PatternKnown at query time
1Order plus all its line itemsorderId
2A customer's orders, newest firstcustomerId
3Pending orders for the fulfilment workerstatus

Base table: pk = ORDER#<orderId>, sk = META for the order, sk = ITEM#0001… for lines. Pattern 1 is one Query on pk = ORDER#A1; the order and its lines come back in sk order from one partition.

GSI1: gsi1pk = CUST#<customerId>, gsi1sk = ORDER#<ISO8601>#<orderId>. Pattern 2 is a Query on GSI1 with ScanIndexForward=False; the timestamp in the sort key gives ordering and date-range filtering.

Python
# boto3, Python 3.12
ddb.create_table(
    TableName="orders",
    BillingMode="PAY_PER_REQUEST",
    AttributeDefinitions=[
        {"AttributeName": "pk", "AttributeType": "S"},
        {"AttributeName": "sk", "AttributeType": "S"},
        {"AttributeName": "gsi1pk", "AttributeType": "S"},
        {"AttributeName": "gsi1sk", "AttributeType": "S"},
    ],
    KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"},
               {"AttributeName": "sk", "KeyType": "RANGE"}],
    GlobalSecondaryIndexes=[{
        "IndexName": "gsi1",
        "KeySchema": [{"AttributeName": "gsi1pk", "KeyType": "HASH"},
                      {"AttributeName": "gsi1sk", "KeyType": "RANGE"}],
        "Projection": {"ProjectionType": "INCLUDE",
                       "NonKeyAttributes": ["status", "total_cents"]},
    }],
)

Pattern 3 is the trap. A GSI keyed STATUS#PENDING puts every pending order in one partition key value. A partition tops out at 1000 WCU / 3000 RCU and 10 GB. At 1 KB per order, 1200 status writes/sec is 1200 WCU on that one key: throttled, and adaptive capacity won't save you because the key is uniformly hot, not isolated. Shard it: gsi1pk = STATUS#PENDING#<shard> with shard = random 0–15 written at order creation, giving ~75 WCU per shard; the worker reads all 16 shards with parallel Query calls. Make the index sparse, delete the attribute when the order leaves PENDING, so it holds only open orders and stays far from the 10 GB ceiling.

Failure modes and how I'd catch them

  • Hot partition: Contributor Insights top-N keys, plus ThrottledRequests and WriteThrottleEvents. Per-partition metrics aren't exposed directly.
  • GSI write throttle: a throttled index write back-pressures the base table write. Watch WriteThrottleEvents on the index, not just the table.
  • Read-after-write through a GSI: GSIs are eventually consistent with no bound, so a create-then-immediately-display flow must read the base table. Catch it with a write-then-read test in CI.
  • Unbounded item collection: every item under one partition key value must stay under 10 GB; a status index that never shrinks will hit it.
  • Pagination: Query returns at most 1 MB, so a customer with 50k orders needs LastEvaluatedKey loops, not a bigger page.

Trade-off

An LSI shares the base table's partition key and throughput and must exist at creation; a GSI has its own keys and throughput and can be added later, but is eventually consistent only. Single-table design buys one-query fetches and costs readability, so I'd use it when the patterns justify it. The real rigidity is that an unplanned question means a new index or a table rebuild, so if the product is still finding its access patterns, I'd keep the write model in DynamoDB and push ad-hoc analytics to S3 exports and Athena rather than trying to make the table answer everything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

What would you use Redis for, and what would you not use it for?

Answer

The 90-second version. Redis is a data-structure server (strings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog) each with server-side operations. So the decision isn't "cache or not". It's two questions: is the data keyed by something you already know, and is losing it survivable? When both hold, Redis is usually the cheapest place to put it. When either fails, it's the wrong tool, and no amount of tuning fixes that.

Assumptions I'd state: single region, Redis 7.x/8.x, default asynchronous replication, working set fits in RAM with headroom.

Where it earns its place

UseWhy it fitsWhat to watch
Cache of computed results or query outputRead by known key, rebuildableSet maxmemory and a policy; measure hit rate
Session storeKey is the session ID; worst case is a re-loginTTL per session; never the only copy
Rate limitingINCR is atomic, counters are tinyExpiry must be atomic with the increment
LeaderboardsZADD / ZRANGE ... WITHSCORES, rank in O(log N)Memory scales with distinct members
Ephemeral queuesLMOVE/BRPOPLPUSH, or Streams with consumer groupsNo built-in dead-letter; you build ack and retry
Pub/sub fan-outFire-and-forget, sub-millisecondNo delivery guarantee and no replay: use Streams if you need either

Where it doesn't

  • System of record. Persistence is configurable, not guaranteed. With appendfsync everysec (the default) a crash can lose up to about a second of acknowledged writes; RDB snapshots lose everything since the last fork. WAIT only confirms replicas received the write: it doesn't fsync them. If you can't reconstruct the data, it doesn't belong here.
  • Querying by value. There's no "find every user with attribute X" without an index you maintain. Redis 8 folds the former Redis Stack modules into the core distribution, so FT.CREATE/FT.SEARCH secondary indexes exist, but they're a separate structure with their own memory and staleness cost, not a property of the data.
  • Large datasets that must all be resident. RAM is the binding constraint and the expensive tier. A 50 GB dataset is a 50 GB bill, plus replication and AOF amplification.
  • Multi-key transactions across a cluster. Cluster shards by hash slot (16384 of them); MULTI/EXEC and Lua scripts only work when every key lands in the same slot. Hash tags ({user:42}:cart) are the workaround, and they concentrate load on one node.

The rate limiter, concretely. Two round trips are not atomic together:

LUA
-- KEYS[1] = rl:{user:42}:<window>, ARGV[1] = window seconds
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return n

Trace: first request in a window. INCR returns 1, so EXPIRE 60 runs, key returns 1. Second request: INCR returns 2, the if is false, TTL untouched, returns 2. The caller rejects above 100. Scripts execute atomically, so nothing slips between the INCR and the EXPIRE. The naive two-command version has a real failure: die between them and the counter has no TTL and leaks forever.

Memory arithmetic. 1M sessions at ~1 KB payload is 1 GB of payload; per-key overhead (dict entry, object header, allocator rounding) pushes a small key toward ~100 bytes, so budget 1.3–1.5 GB, and leave headroom for the RDB fork, whose copy-on-write can push RSS toward 2×.

Failure modes, and how you'd see them. The default maxmemory-policy is noeviction: at the limit, writes fail with an OOM error while reads keep working. Watch the OOM count in INFO errorstats and used_memory against maxmemory. Switch to allkeys-lru and you stop erroring but start evicting things you cared about, lock keys and rate-limit counters included: watch evicted_keys. An unbounded key space is the incident; every key wants a TTL or a deliberately chosen policy.

Locks. A naive SET key val NX PX 30000 is unsafe under partitions and clock skew, and the Redlock debate (Kleppmann vs. antirez, 2016) never resolved in its favour. Where double execution is genuinely harmful, put the guarantee in a database constraint or use a fencing token, and treat the lock as an optimisation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How do you choose and name keys and data structures in a key-value store such as Redis for a given access pattern, and how do TTLs, eviction policies and memory limits change that design?

Answer

Start from the access pattern, not the data model. In a key-value store the key is the query, so you design the key to answer the question in one round trip. Then pick the smallest structure that supports the operations you need, and set TTL and eviction to match the value's lifetime and the memory budget.

Worked example: user sessions. Access pattern: read and update a session by user ID, expire after 30 minutes of inactivity. Key: sess:{user_id}. Structure: hash, because you update individual fields (last_seen, cart_id) without rewriting the whole value. TTL: EXPIRE sess:{user_id} 1800 on every write. Eviction: if sessions are the only data, allkeys-lru; if the instance also holds critical data, volatile-lru so only keys with TTL are evicted. Memory: 1M sessions × 1 KB ≈ 1 GB; set maxmemory 2GB to leave headroom for fragmentation and replication buffers.

Key naming. Use colon-separated namespaces: app:entity:id:field. Include a version when the shape may change: v2:sess:{user_id}. Avoid spaces and mixed case. In Redis Cluster, use hash tags {user_id} to keep multi-key operations on one slot. The key is the only index, so if you need a second access pattern (e.g., sessions by device), you must write a second key or use a secondary structure like a set.

Structure selection. Match the structure to the operations, not the data's shape.

Access patternStructureKey example
Get/set whole valueStringcfg:feature_flags
Update fieldsHashsess:{user_id}
Ranked listSorted setleaderboard:global
Membership testSetpost:{id}:likers
Append-only logStreamevents:{room_id}

TTL and eviction. TTL is a correctness tool: it bounds staleness and prevents leaks. Add jitter, EXPIRE key (1800 + rand(0,300)), so a batch of keys written together does not expire together and stampede the origin. Eviction policy is a data-loss decision: noeviction returns errors on writes when full, allkeys-lru evicts any key, volatile-lru only keys with TTL. If losing a key breaks correctness, it does not belong on an evicting instance.

Failure modes. A hot key (global counter) saturates one shard; shard it or aggregate locally. A missing TTL turns a cache into a leak. maxmemory set too close to the dataset causes constant eviction and misses; monitor evicted_keys and keyspace_hits/misses. Large keys (a hash with millions of fields) block the event loop during deletion; split them.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

When is a graph database the right choice, and when is it not?

Answer

A graph database stores nodes, relationships and properties, with relationships as first-class objects. Each node holds direct references to its relationships, so traversing to neighbours follows direct adjacency rather than searching all relationships; overall cost still depends on the nodes and edges visited. That is the whole technical argument, and it is a real one.

It matters when traversal is both central and deep or variable-depth. Social connection paths, recommendation via shared attributes, fraud rings where the pattern is the connection structure, dependency and impact analysis, permission hierarchies with inheritance. In SQL these are recursive CTEs whose cost compounds per level, and expressing 'find any path up to six hops matching this pattern' is genuinely awkward, whereas in a graph query language it is the natural thing to write.

It is not justified by having many-to-many relationships. That is a junction table. Nor by one or two joins to fetch a user's connections: that is an ordinary query. Nor by the data 'feeling like a graph', which almost all data does when you look at it that way. The most common mistake I have seen is adopting a graph database for a problem two joins would solve, then paying in operational unfamiliarity, a smaller ecosystem, fewer people who can debug it at 3am, and weaker tooling.

There are also real limits on the other side. Graph databases are generally less suited to aggregate analytics over the whole dataset, and distributing a graph across machines is genuinely hard because traversals cross partitions unpredictably, which is why very large graphs are a specialist problem rather than a scaling knob.

The middle path worth considering: keep the system of record relational and project the graph-shaped subset into a graph store for the traversal workload. That keeps transactions and constraints where they belong and confines the graph store to what it is good at: at the cost of a synchronisation pipeline, which must be justified in turn.

My threshold: if I cannot name a query that is genuinely awkward in SQL and central to the product, I would not adopt one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

When modeling variable-depth relationships like fraud rings or recommendation paths, what mechanical advantage does index-free adjacency offer over recursive SQL joins?

Answer

What a strong candidate says first

Index-free adjacency removes the global index lookup from every hop. A node record stores a direct pointer to its first relationship record; relationship records form a doubly linked list per node, so following an edge is a pointer dereference: one page access, O(1), independent of how many edges exist in the database. Recursive SQL does the opposite: each hop probes a global edge table through a B-tree, costing O(log N) page reads for the descent plus the matching leaf entries, and each iteration materializes the frontier as an intermediate result set before the next one runs.

The asymptotic difference is real, but be honest about the constant: a B-tree over 10^9 rows is typically 4–5 levels deep, so a single indexed hop is a handful of page reads, not a catastrophe. The gap shows up at depth and at scale: SQL re-materializes a frontier that grows as k^d, and its probe cost tracks total table size N, while the graph walk's cost tracks only the subgraph it visits.

Worked trace

Fraud ring, 3 hops, average degree k = 20, edge table of 10^9 rows, index on edges(from_id).

PostgreSQL WITH RECURSIVE:

  • Hop 1: 1 index probe → 20 edges. Frontier = 20.
  • Hop 2: 20 probes → 400 edges. Frontier = 400.
  • Hop 3: 400 probes → 8,000 edges. Frontier = 8,000.
  • 421 index probes total; each is a ~4-level descent plus leaf reads. Each iteration also writes and re-reads a working table of 20, 400, then 8,000 rows.

Neo4j:

  • Start at node A's record, follow firstRelId → 20 relationship records → 20 target nodes.
  • 8,420 pointer dereferences total (20 + 400 + 8,000). No global index touched, no intermediate table. A node's relationships sit in adjacent records, so most dereferences hit pages already in cache.

Same edges touched; the difference is 421 B-tree descents and three materializations versus 8,420 pointer chases.

Comparison

Recursive SQLIndex-free adjacency
Per-hop costO(log N) descent + k leaf readsO(1) dereference per edge
Total, depth dO(k^d · log N)O(k^d)
Cost depends ontotal edge count Nvisited subgraph only
Frontiermaterialized working table per iterationin-memory pointer set
Plannerrecursive term planned once; can't adapt to actual frontier sizeno planning step

Failure modes

  1. Supernodes. A merchant with 500,000 edges turns the linked-list walk into a long scan with cache misses. SQL with an index on (from_id, rel_type) can filter by type cheaply. Mitigation: filter by relationship type, add a relationship-property index, or split into bucket nodes.
  2. Cycles. UNION ALL loops forever on a cycle unless you carry a visited set:
SQL
WITH RECURSIVE ring AS (
  SELECT from_id, to_id, 1 AS depth, ARRAY[from_id] AS path
  FROM edges WHERE from_id = 42
  UNION ALL
  SELECT e.from_id, e.to_id, r.depth + 1, r.path || e.from_id
  FROM edges e JOIN ring r ON e.from_id = r.to_id
  WHERE r.depth < 4 AND NOT e.to_id = ANY(r.path)
)
SELECT * FROM ring;

The path array costs memory proportional to depth and is re-copied each iteration. Graph traversal enforces relationship uniqueness within a path by default, so cycles terminate without bookkeeping.

  1. Distribution. Pointer dereference assumes the neighbor is on the same machine. Shard the graph and a microsecond dereference becomes a network round trip; partitioned SQL joins have the same problem but the planner can hash-join or broadcast.

  2. Bulk aggregation. "Average balance across all accounts" is a contiguous columnar scan; pointer chasing walks fragmented records and loses badly.

When not to use it

If the workload is 1–2 hop lookups or global aggregations, a relational store with good indexes is fine and you avoid running a second system. Index-free adjacency earns its keep on deep, selective traversals where the frontier stays small relative to N.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain the trade-offs of storing JSON in a relational database versus a document store.

Answer

The question is really "where does the schema boundary sit", and the honest default for most applications is a relational database with a native JSON column. Reach for a document store when the document is the unit of read and write, not when you have a few variable fields.

How each one actually stores it. PostgreSQL's jsonb (9.4+; json since 9.2) is a binary, key-deduplicated, order-losing representation. You index it with GIN: jsonb_ops (the default) supports @>, ?, ?|, ?&; jsonb_path_ops supports only @>, @?, @@ and is smaller and faster for containment. MySQL 5.7+ has a JSON type but no direct index: you index a generated column, or use a multi-valued index (8.0.17+) over CAST(... AS ... ARRAY). MongoDB stores BSON, caps a document at 16 MB, and indexes array elements with multikey indexes.

The three things that actually bite.

  1. No partial reads. A jsonb value over ~2 KB is TOASTed out of line. Reading payload->>'status' detoasts and decompresses the whole document, so a 40 KB document costs 40 KB of I/O for one field.
  2. No partial writes. jsonb_set returns a new value and MVCC writes a new row version; there is no in-place field update, unlike MongoDB's $set, which can update a field in place when the document does not grow. Illustrative arithmetic: 50M rows × 40 KB payload = 2 TB; updating status on 1% of rows rewrites 500K × 40 KB = 20 GB and leaves 20 GB of dead tuples for autovacuum.
  3. No per-key statistics. The planner has no distribution for payload->>'status', so it falls back to a fixed default selectivity instead of the real one and picks bad plans on large tables. Fixes: CREATE STATISTICS on the expression (PG 10+), or a GENERATED ALWAYS AS ... STORED column (PG 12+) with a btree index, which is also the migration path off JSON for a field that turned out to be fixed.

What the document store buys. Sharding is built in (mongos plus config servers, hashed or ranged shard keys) rather than bolted on; Postgres has declarative partitioning (10+, hash in 11) and Citus, but no built-in sharding. Aggregation pipelines and $lookup (3.2+) are natural for nested data. $jsonSchema validators (3.6+) give schema enforcement where you want it. And multi-document transactions exist (4.0 on replica sets, 4.2 on sharded clusters), so "no transactions" is no longer the argument.

What the relational option buys. One transaction spanning the document and the relational columns; foreign keys and constraints on the structured parts; SQL for reporting; one backup, one failover story, one set of on-call skills.

Failure modes to name. A JSON column holding fields that are fixed and known: that is a migration someone avoided, and it costs more later than the migration would have. A table that is one giant JSON column with no relational neighbours: you have built a worse document store. And a GIN index on a key-rich document can approach the size of the data itself, so index bloat is a real budget line.

Default: relational plus jsonb when the data is mostly relational with variable parts. Dedicated store when the document is the access unit, nesting is deep, and the workload is document-centric.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do tombstones affect read performance and compaction in distributed wide-column stores like Cassandra, and how do you design against tombstone-related latency spikes?

Answer

In LSM-based wide-column stores like Cassandra, a delete does not overwrite or remove data in place on disk. Disk SSTables are immutable. Instead, a delete is a write of a marker called a tombstone containing the deleted row or cell key and a deletion timestamp.

The Read Path Problem

When executing a read query, the coordinator reads from multiple SSTables and the Memtable, merging results via a priority queue to reconstruct the current row state.

Tombstones affect reads because the engine must scan over them to ensure there are no older or concurrent writes they mask. If a table models a queue or updates nullable columns frequently, a single partition can accumulate tens of thousands of tombstones:

SSTable A: [Row 1: active] -> [Row 2: tombstone] -> [Row 3: tombstone] ... -> [Row 5000: active]
Query: SELECT * FROM t WHERE pk = 'x' LIMIT 10;

To satisfy LIMIT 10, the storage engine reads and deserializes 5,000 tombstone cells off disk into memory before returning 10 live rows. In Cassandra, scanning past default thresholds (tombstone_warn_threshold = 1,000; tombstone_failure_threshold = 100,000) causes p99 latency to jump from 5 ms to multi-second timeouts, or crashes the query outright with a TombstoneOverwhelmingException.

Compaction and gc_grace_seconds

Tombstones are permanently purged only during SSTable compaction. However, a tombstone cannot simply be discarded when merged. It must be retained for at least gc_grace_seconds (default: 864,000 seconds / 10 days) across the cluster.

Setting / FactorImpact on Tombstone Removal
gc_grace_secondsPrevents deleted data from being resurrected by a replica that was offline during the delete. Tombstones younger than this window cannot be dropped.
Compaction StrategySize-Tiered (STCS) compacts SSTables of similar sizes; a tombstone in a large SSTable may wait months for compaction. Leveled (LCS) compacts predictably across levels, purging tombstones faster.
Overlapping SSTablesA tombstone cannot be dropped during compaction if an older SSTable contains the cell being deleted and is not part of that same compaction run.

Anti-Patterns and Design Solutions

  1. Do not use wide-column stores as job queues: The pattern of inserting work items and immediately deleting them on completion generates continuous tombstone pressure. Use dedicated brokers (Kafka, SQS) instead.
  2. Avoid null inserts: Inserting a null value in Cassandra writes a cell tombstone. Applications should omit unset fields in the CQL statement or prepare explicit statements for populated fields.
  3. Bucket partitions by time (TTLs + TWCS): If deleting time-series data, set a TTL instead of issuing manual DELETE statements, and use TimeWindowCompactionStrategy (TWCS). TWCS groups data into time-windowed SSTables; once an entire SSTable exceeds the TTL window, the file is dropped instantly as an OS unlink without scanning or compaction overhead.
  4. Partition splitting (Immature writes vs. Deletes): Instead of deleting rows inside a single wide partition, rotate partitions (e.g., (user_id, bucket_epoch)). When data is obsolete, query new buckets or drop old partitions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Walk me through the write path of a log-structured store like Cassandra (commit log, memtable, SSTables, compaction) and what the compaction strategy choice does to read and write amplification?

Answer

The write path, in one pass. A write appends to the commit log, a sequential file on disk, and goes into the memtable, an in-memory sorted structure. Both succeed, the coordinator acknowledges. Nothing is read first: no read-modify-write, no B-tree page located and updated in place. That is why a log-structured store sustains writes proportional to the append rate rather than to dataset size.

The memtable flushes to an immutable SSTable once the combined memtable size crosses memtable_cleanup_threshold (a fraction of the memtable_heap_space budget). SSTables are never modified. An update is a new cell with a newer timestamp; a delete is a tombstone. Compaction merges SSTables later, keeping the newest cell per key and dropping shadowed ones.

Trace: a 1 KB write, RF=3, commitlog_sync: periodic (the default, 10 s). The coordinator appends to its commit log, writes the row to its memtable, forwards to two replicas that do the same, then acks the client. Client-visible latency is a memory write plus a sequential append: single-digit milliseconds. The durability caveat: with periodic sync, a power loss can lose up to commitlog_sync_period (10 s) of acknowledged writes on all three replicas at once. batch mode fsyncs before every ack and costs you the throughput.

Read amplification is the price of immutability. A read checks the memtable and every SSTable that might hold the key. Bloom filters (bloom_filter_fp_chance, default 0.1 under STCS, 0.01 under LCS) eliminate most candidates, but every one that passes is read and merged. Read cost therefore scales with SSTable count, and compaction is the thing holding that count down, not housekeeping.

STCSLCSTWCS
write amplowest, order 4xhighest, order 10xlow inside a window
read ampgrows with tier count~90% of reads hit one SSTablegrows with window count
space ampup to 50% obsolete data~10%low; whole windows dropped on TTL
fitswrite-heavy, generalread-heavy, update-heavytime series with TTL

Choosing. STCS merges similarly sized SSTables: cheap on writes, but a large tier can sit unmerged for a long time and you must keep roughly 50% disk free. LCS keeps fixed-size SSTables (default sstable_size_in_mb 160) in levels with a 10x size ratio; reads touch few files, but every byte is rewritten about ten times as it descends the levels, so write throughput drops and compaction I/O competes with the write path. TWCS groups SSTables by time window and never rewrites closed windows, so TTL expiry drops whole files, but a late write into an old window creates overlapping SSTables that TWCS handles badly.

Failure modes and detection. Compaction falling behind shows as PendingCompactions climbing, a growing backlog in nodetool compactionstats, and read p99 rising because SSTables-per-read climbs. Under STCS that ends in disk exhaustion; under LCS it ends in write stalls when L0 fills. Watch nodetool tablehistograms for SSTables-per-read and read latency percentiles, and nodetool tablestats for live SSTable count and space used.

When not to. If the workload is read-modify-write, or needs many secondary indexes, the compaction tax is permanent. That is a case for a B-tree store, not a tuning problem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Explain when denormalisation is the design rather than a compromise.

Answer

In a relational database, denormalisation is a deliberate exception: you normalise by default and duplicate where a measured read pattern demands it, accepting an obligation to keep copies consistent.

In a wide-column or access-pattern-driven store, duplication is the normal case. You model per query, so the same data lives in several tables shaped for different reads. Nobody considers this a compromise; it is how the model works, because the store's constraint, single-partition reads, makes it the only way to serve several access patterns.

The reason it is tenable there is that these stores are built for it. Writes are cheap and expected to fan out to several tables. There is no join, so there is no alternative. And there is no query planner to be denied the chance to optimise, because there was never going to be one.

What stays the same in both worlds is the obligation. Duplicated data can diverge, and the design must say what keeps it consistent: writing all copies in one batch where the store supports it, an asynchronous process, or accepting a stated staleness window. And there must be a way to detect divergence, a reconciliation check, because duplicated data drifts and drift that nobody checks for is found by a user.

The distinction I would draw for either world is between duplicating a current value and storing a point-in-time fact. An order line's price at purchase is not duplication at all; it is a different fact from the product's current price, and storing it is correct in every model. Confusing the two leads either to unnecessary synchronisation machinery, or to historical records silently rewriting themselves when a source value changes.

So: in relational, duplication needs a justification. In access-pattern stores, it needs a plan, because it is happening either way, and the only question is whether the consistency mechanism was designed or improvised.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How would you model a social feed, and which store would you use?

Answer

The defining question is fan-out on read versus fan-out on write, and the honest answer is usually both.

Fan-out on read stores each post once and assembles a feed by querying the posts of everyone a user follows, ordered by time. Writes are cheap and there is one copy of the truth, so edits and deletions are trivial. Reads are expensive and get worse as following counts grow.

Fan-out on write pushes each post into a materialised feed for every follower at post time. Reads are a single sequential fetch, which is what a feed needs. Writes are expensive proportional to follower count, storage multiplies, and edits or deletions must propagate to every copy.

The standard resolution is hybrid: fan-out on write for ordinary users, and fan-out on read for accounts with very large follower counts, whose posts are merged in at read time. That avoids a single post triggering millions of writes while keeping the common case fast. The threshold is measured, not guessed.

On stores: the posts themselves belong in a relational database or a document store. They are entities with relationships, need constraints and moderation workflows, and benefit from transactions. The materialised feeds suit a key-value or wide-column store keyed by user with a time-ordered sort key: it is append-heavy, read by known key, and rebuildable from the posts, which is exactly the profile that suits those stores. A cache in front for the hot recent window of active users. And the follow graph stays relational unless the product does deep traversal, 'friends of friends who liked this', in which case a graph store for that specific workload is worth considering.

The property that makes this architecture safe is that the feed store is derived: it can be rebuilt from posts and follows, so an inconsistency is repairable rather than a data loss. I would design the rebuild path from the start, because it will be needed (for a bug, a backfill, or a ranking change) and retrofitting it is painful.

And I would question the requirement first: strict chronological ordering across sources is much harder than it sounds, and if the product ranks the feed anyway, that relaxes the ordering guarantee considerably and simplifies the design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Explain how you would model a chat application's message storage.

Answer

Messages are a good fit for a partitioned store because the access patterns are narrow and stable: fetch recent messages in a conversation, paginate backwards, and append. That is retrieval by known key with a time-ordered range, which is exactly what partition-plus-sort-key models serve well.

The model: partition by conversation, sort by a time-ordered identifier. The primary read, the most recent N messages in a conversation, is then a single-partition query, and pagination backwards is a range within the same partition.

The identifier should be time-ordered but unique, not a plain timestamp: two messages can share a millisecond, and ordering must be deterministic or pagination skips and repeats. A time-ordered unique identifier such as ULID or UUIDv7 handles both.

Bounding the partition is the issue that decides whether the design survives. A busy conversation accumulates messages forever, and an unbounded partition becomes a problem regardless of store. So the partition key is usually compound, conversation plus a time bucket, with reads spanning buckets when they cross a boundary. That is more read complexity for bounded partitions, and it is the right trade.

What does not fit this store: search across messages, which needs a search index; user-level aggregate queries like 'all messages mentioning me', which needs either a separate table written at message time or a search index; and anything ad-hoc.

Read state, which messages a user has read, is a separate concern with a different access pattern, keyed by user and conversation, and usually a small mutable record rather than per-message flags, which would multiply writes by participant count.

The things I would confirm before committing: whether messages are editable or deletable, since that affects immutability assumptions and any derived indexes; retention policy, since it determines whether time-bucketed partitions can simply be dropped; and whether strict ordering is required across devices, which is harder than it sounds when clients have clock skew. Server-assigned ordering is the usual answer and worth deciding explicitly.

And I would keep conversation and participant metadata relational, because that part has genuine relationships, constraints and permission rules: with messages in the partitioned store. That split plays to each model's strength rather than forcing one to do both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How would you migrate data from a relational database to a document store safely?

Answer

Incrementally, with the ability to abandon it at every stage, because a migration that can only succeed is a migration that will hurt when it does not.

Model first, and not as a copy. Translating tables to collections one-for-one produces a relational schema in a store that cannot join it: the worst of both. The document model must be derived from access patterns, which means deciding what is embedded and what is referenced before any data moves.

Dual-write. Write to both stores, with the relational one remaining authoritative. This exercises the write path under real traffic and reveals modelling problems while they are still cheap. Failures writing to the new store must not fail the request, but they must be recorded, and a rising failure rate is the signal to stop and reconsider.

Backfill existing data in batches, idempotently, so it can be re-run and resumed. Then reconcile: compare the two stores continuously and alert on divergence. Reconciliation is where the real problems surface: it is routine to find the dual-write missing an edge case that no test covered.

Shadow reads. Read from the new store, compare against the relational result, log differences, but serve the relational answer. This validates the read path against production traffic with no user risk, and it is the step most often skipped and most often regretted.

Cut over reads gradually (a percentage, or a subset of endpoints) with an instant rollback switch. Then, after a period of confidence, make the new store authoritative and stop dual-writing.

Throughout, the relational database stays capable of serving everything until the very last step, which is what makes each stage reversible.

The things I would decide before starting: what specifically is being fixed, and how will we know it worked; what the rollback plan is at each stage; and what happens to reporting, which usually depended on SQL and is frequently discovered mid-migration.

And I would set an explicit abandonment criterion up front. Migrations acquire sunk-cost momentum, and deciding in advance what would make stopping the right answer is what makes stopping possible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

A team wants to move from PostgreSQL to MongoDB for schema flexibility. How do you respond?

Answer

What I'd say in the first two minutes

"Schema flexibility" is a symptom name, not a diagnosis. Before evaluating MongoDB I'd want the concrete case: which records carry attributes others don't, and what breaks today. In practice it resolves into three complaints, and only one is a modelling problem.

  1. Migrations are slow or scary to deploy: a migration-process problem, not a database problem.
  2. Adding a column needs coordination across services: same.
  3. Some records genuinely carry attributes others don't: PostgreSQL handles this with jsonb.

So my answer is: I'd push back on the stated reason, show that 1 and 2 are fixable in place and 3 is already supported, and only then consider a narrow proof if the workload is genuinely document-shaped.

Migrations and variable attributes are not the blocker

SQL
-- 1. Adding a column: PG 11+ keeps a non-volatile default in the catalog,
--    so this does not rewrite the table. ACCESS EXCLUSIVE is held for milliseconds.
ALTER TABLE orders ADD COLUMN channel text NOT NULL DEFAULT 'web';
ALTER TABLE orders ALTER COLUMN channel DROP DEFAULT;  -- future inserts must be explicit

-- 2. A constraint needing a full scan: validate without blocking writers.
ALTER TABLE orders ADD CONSTRAINT channel_known
  CHECK (channel IN ('web','ios','android','partner')) NOT VALID;  -- SHARE UPDATE EXCLUSIVE
ALTER TABLE orders VALIDATE CONSTRAINT channel_known;              -- SHARE UPDATE EXCLUSIVE

-- 3. Genuinely variable attributes: one JSON column, still one transaction.
ALTER TABLE orders ADD COLUMN attrs jsonb NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE orders ADD CONSTRAINT attrs_is_object CHECK (jsonb_typeof(attrs) = 'object');
-- CONCURRENTLY cannot run inside a transaction block; on failure it leaves an
-- INVALID index you must drop and retry.
CREATE INDEX CONCURRENTLY orders_attrs_gin ON orders USING gin (attrs jsonb_path_ops);

SELECT id, total FROM orders WHERE attrs @> '{"carrier":"dhl"}';  -- uses the GIN index

jsonb_path_ops is smaller and faster than the default jsonb_ops but only serves containment (@>); if you also need key-existence operators, use jsonb_ops.

What the migration actually costs

Guarantee you have todayMongoDB counterpartWhere it stops
CHECK/FK enforced for every writer, including scripts$jsonSchema validator per collection (3.6+)opt-in per collection; validationLevel: "moderate" does not re-check already-invalid documents on update; no cross-collection invariants
Multi-statement transactions, no default time limitmulti-document transactions (4.0 replica sets, 4.2 sharded)transactionLifetimeLimitSeconds defaults to 60s; abort and retry handling moves into application code
Joins and ad-hoc SQL for reporting$lookup in the aggregation pipelineper-document lookup, no cost-based join planning across collections; reporting usually ends up in a warehouse anyway

The failure mode that shows up six months later

A backfill script writes {_id, total} with no attrs. Nothing rejects it. A reader doing doc.attrs.carrier gets undefined; an aggregation $match: {"attrs.carrier": "dhl"} silently omits the row. The symptom is a wrong number in a report, not an exception. Detection: run a nightly count of documents failing the $jsonSchema validator and alert on it being non-zero, if that metric doesn't exist, you have no schema, only a convention.

What I'd propose instead

If after that the workload is genuinely document-shaped (one aggregate read and written whole, no cross-entity invariants) prove it on one bounded use case, in parallel, with a reconciliation job comparing both stores, and measure it. Operational plan first: backup and restore actually rehearsed, monitoring, and on-call familiarity with the new failure modes.

My position isn't that MongoDB is wrong. It's that this justification doesn't survive examination, and a migration made for the wrong reason costs a dual-write period measured in weeks and doesn't fix the pain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

What would make you recommend against a NoSQL store for a new project?

Answer

The signals that most strongly favour staying relational:

Unknown or evolving access patterns. A new product's queries change constantly. Access-pattern-driven stores require confident knowledge up front, and being wrong means a new table and a backfill. A relational database lets you ask questions you did not anticipate, which is exactly what early product work needs.

Genuine relational structure. Entities with meaningful relationships, where integrity across them matters. If the domain is relations, use the model built for them.

Multi-entity transactions. If several things must change atomically, that is a relational strength and its absence elsewhere is a large ongoing cost.

Reporting and analytics matter. SQL is what every BI tool and analyst uses. Moving off it means building a pipeline back, and that cost is regularly discovered late.

Constraints matter. If invalid data would be genuinely costly, declared constraints enforced for every writer are worth a great deal, and moving them into application code weakens them to the discipline of the least careful writer.

Modest scale. Most systems never exceed what a well-indexed relational database on one machine handles, and that is a much larger number than people assume. Choosing for scale you do not have pays the flexibility cost immediately for a benefit that may never arrive.

Team unfamiliarity. If nobody can operate the new store at 3am, that risk is transferred to whoever is on call, and it is real.

The motivations I would question specifically: schema flexibility to avoid migrations, which trades a one-time cost for permanent ambiguity; anticipated scale without measurement; and 'the data feels document-shaped', which usually means the first screen resembles a document and does not survive the second.

What would change my mind: a workload genuinely unsuited to the relational model. Caching, full-text search, deep graph traversal, extreme write volume with known keys, or a measured limit already being hit. Those are good reasons, and I would move readily on them.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How would you decide between polyglot persistence and one database?

Answer

My default is one database, and each additional store must earn its place against a cost that is consistently underestimated.

The costs are mostly operational rather than technical. Every store needs backups that are tested, monitoring with meaningful alerts, upgrade and patching processes, capacity planning, and enough people who understand it to handle an incident at 3am. That last one is the real constraint in most teams: a second store with one expert is a single point of failure in the staffing sense.

Then there are the data costs. There is no join across stores, so any query spanning them moves into application code. There is no transaction across them, so keeping them consistent becomes your problem: typically an outbox or a reconciliation process, both of which are real systems needing their own monitoring. And there will be a window where they disagree, which someone must decide how to present.

So I would add a store when there is a workload the primary genuinely cannot serve and the gap is material. A cache is the clearest case: an in-memory store for hot reads, where the data is derived and losing it is harmless, so most of the consistency cost does not apply. A search index is another: full-text search with relevance ranking is genuinely different work, and accepting eventual consistency between the source and the index is usually fine.

What I would push back on is adding a store because it fits one part of the model more elegantly. Elegance is not worth an operational system, and the elegance usually erodes once synchronisation code appears.

Before adding one, I would check what the primary can now do (relational JSON, full-text search, materialised views, listen/notify) because these have improved considerably and often close the gap well enough.

And if a second store is genuinely justified, I would define its ownership boundary sharply: one store is the system of record, the other is derived and rebuildable from it. Two stores that are both authoritative for overlapping data is the arrangement that produces unresolvable inconsistencies, and it is worth avoiding by design rather than discovering later.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Describe a case where you would deliberately use two different stores together.

Answer

The clearest case is full-text search alongside a relational system of record.

An e-commerce catalogue lives relationally: products, categories, prices, inventory, with constraints, transactions and referential integrity. That is genuinely relational data and belongs there.

But product search: typo tolerance, relevance ranking, faceting, synonyms, partial matching across several fields: is different work. Relational full-text search exists and is decent, but a dedicated search engine is substantially better at relevance, and relevance is directly a conversion problem, so the difference has business value rather than being an engineering preference.

The arrangement: the relational database is the system of record, and the search index is derived and rebuildable. Products are written relationally; a pipeline projects them into the index: ideally via an outbox so the write and the projection cannot diverge silently.

That boundary is what makes it safe. The index can be rebuilt from the source at any time, so an inconsistency is a repairable annoyance rather than data loss. I would build and test the rebuild path from the start, because it will be needed (for a mapping change, a bug, or a backfill) and retrofitting it under pressure is unpleasant.

The consequences to design for: the index is eventually consistent, so a product edited in the admin console may not appear updated in search for a few seconds. Usually fine, but the admin UI should read from the source rather than the index so the person who just made the change is not confused. Search results should also be re-validated against the source before acting on them: checking a product is still in stock at add-to-cart, rather than trusting the index.

What justifies this and not most polyglot proposals: the workload is genuinely different in kind, the derived store owns nothing, and losing it entirely costs a rebuild rather than any data. When a proposal cannot claim all three, I would look at it much harder.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

How would you explain the SQL versus NoSQL decision to a non-technical stakeholder?

Answer

What I'd say in the first two minutes

Both options store the same data. The difference is what each is built to be good at. The relational option is a general-purpose filing system: it enforces rules so bad data cannot get in, and it can answer questions we have not thought of yet. The specialised option is a purpose-built machine: much faster at one specific job, and expensive to repurpose.

Then three numbers, because stakeholders decide on numbers, not adjectives. The figures below are the illustrative set I would use for a mid-size e-commerce company: swap in the real ones before the meeting.

Questions we have not asked yet. "We do about 40 million orders a year: 1.3 a second on average, peaking near 50 on Black Friday. On the relational option, a new report is a query: joining orders, customers and refunds across a 200 GB database returns in seconds once the index exists, and building that index on the live table takes tens of minutes without blocking writes. On the specialised option, the data is laid out for the questions we listed at the start. A question we did not list means a full scan: 500 GB at a provisioned 10,000 read units a second is 65.5 million read units and about 1.8 hours per pass. Before anyone writes the aggregation. Realistically it is a new index and a backfill, so days to weeks."

Data quality. "The relational option can guarantee every order belongs to a real customer: a foreign key the database enforces at write time. The other one relies on our code being correct everywhere, forever, including code written by people who have not joined yet."

Scale. "The specialised option handles volume we do not have. A single relational instance on 4 vCPUs sustains low thousands of simple writes a second and keeps indexed point reads at a few milliseconds p99. We are at 1.3 writes a second average. We would be paying the flexibility cost now for headroom we would need at roughly a thousand times our current peak."

Recommendation with a tripwire. "I recommend the relational option. The signal that changes my mind: sustained writes above about 2,000 a second, or a single table past roughly 1 TB where the working set no longer fits in RAM. At that point the migration is a quarter or two of one engineer's time plus dual-write plumbing, and we revisit."

What I would ask them. Not to adjudicate between two databases. Which constraints matter: how much unanticipated reporting is worth, how bad incorrect data would be, what growth they actually expect. Those are genuinely their questions.

What they askRelationalSpecialised
A report we did not planQuery, seconds with an index; index build tens of minutes on 200 GBFull scan: 65.5M read units, ~1.8 h per pass at 10,000 RCU/s, then a backfill
Bad dataForeign key rejects it at write timeApplication code must be right everywhere, forever
Our volume1.3 writes/s average, ~50/s peakBuilt for tens of thousands/s
Headroom~1,000x current peakUnused

I would avoid presenting it as a technology preference, and avoid asking them to choose between two things they cannot evaluate. Their input is on which constraints matter, not on which engine wins.

Curated: · Written: · Reviewed:

Difficulty: Medium