Skip to content
System Design

NoSQL interview questions and answers

35 questions, 21 with code. About 2 h 9 min to read them all.

By TestLab · Updated

Plan for an interview
35 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What are the main types of NoSQL databases, with examples?

There are four main families of NoSQL databases: key-value stores (Redis, Amazon DynamoDB), document stores (MongoDB, Couchbase), wide-column (column-family) stores (Apache Cassandra, HBase, ScyllaDB) and graph databases (Neo4j, Amazon Neptune). Each uses a different data model optimized for particular access patterns. Time-series and search engines are related specialized stores.

Read full answer

Applies toNoSQL database selection and system design

The Four Families

Type Data model Example databases Best for
Key-value A key mapped to an opaque value Redis, DynamoDB, Memcached (cache), Riak Caching, sessions, counters, simple lookups by ID
Document JSON-like documents with nested fields MongoDB, Couchbase, Amazon DocumentDB, Firestore Product catalogues, user profiles, content, varied attributes
Wide-column Rows with a partition key and many sorted columns Cassandra, ScyllaDB, HBase, Google Bigtable Write-heavy time series, IoT, event logs at large scale
Graph Nodes and edges with properties Neo4j, Amazon Neptune, JanusGraph Social networks, recommendations, fraud rings, network topology

Note: DynamoDB is often described as both key-value and document, because items can hold nested attributes.

Short Examples

Key-value (Redis)

SET session:9f2a "{\"userId\": 42, \"cart\": 3}" EX 1800
GET session:9f2a

Document (MongoDB)

{"_id": "p1001", "name": "Running Shoe", "price": 89.99,
 "sizes": [7, 8, 9, 10], "specs": {"weight_g": 240, "drop_mm": 8}}

Wide-column (Cassandra CQL)

CREATE TABLE sensor_readings (
  sensor_id text, reading_time timestamp, temperature double,
  PRIMARY KEY ((sensor_id), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);

Graph (Neo4j Cypher)

MATCH (u:User {id: 42})-[:FRIEND]->(:User)-[:FRIEND]->(fof:User)
WHERE fof <> u
RETURN DISTINCT fof.name LIMIT 10

Related Specialized Stores

  • Time-series databases (InfluxDB, TimescaleDB, Prometheus storage): optimized for timestamped metrics, downsampling and retention.

  • Search engines (Elasticsearch, OpenSearch): full-text search, relevance ranking, aggregations; usually a secondary store fed from a primary database.

How to Choose

  • Lookups by a single key, very low latency: key-value.

  • Self-contained entities with nested or varied fields, queried by several attributes: document.

  • Huge write volumes with queries by partition and time range: wide-column.

  • Queries that follow many relationships (multi-hop): graph.

Trade-offs

NoSQL stores are designed around known access patterns. Ad-hoc queries, joins and cross-entity constraints are harder than in relational databases. Many NoSQL systems now support transactions (MongoDB multi-document transactions, DynamoDB transactions), but with limits on scope and cost.

Interview Tip

Name the four families, an example database and a typical use case for each, and say that the choice depends on access patterns. A common mistake is saying “NoSQL means no schema and no transactions”; schemas move into the application, and many stores now support transactions.

2

What is eventual consistency and what role does it play in NoSQL?

Eventual consistency is a consistency model in which, if no new updates are made to a piece of data, all replicas will eventually converge to the same value. In the meantime, reads may return stale data. Many distributed NoSQL databases use it (by default or as an option) so they can stay available and fast across replicas and data centres, trading immediate consistency for lower latency, higher availability and better write scalability.

Read full answer

Applies todistributed NoSQL databases (Cassandra, DynamoDB, Riak, Couchbase cross-data-centre replication, MongoDB reads from secondaries)

How It Happens

  1. A client writes price = 90 to one replica (or a subset of replicas).

  2. The write is acknowledged quickly.

  3. Replication propagates it to other replicas asynchronously, usually within milliseconds, but potentially longer during failures or heavy load.

  4. A read from a replica not yet updated returns the old price = 85.

  5. Eventually all replicas show 90.

Why NoSQL Databases Use It

  • Availability: writes can succeed even if some replicas are down or partitioned.

  • Low latency: no need to wait for every replica (including those in distant regions) before acknowledging.

  • Multi-region scaling: users in each region read and write locally.

  • Throughput: less coordination between nodes.

Mechanisms That Make Replicas Converge

Mechanism Purpose
Asynchronous replication Propagates writes in the background
Hinted handoff (Cassandra, Dynamo-style systems) Stores writes for a down node and delivers them when it returns
Read repair Fixes stale replicas detected during reads
Anti-entropy repair (Merkle trees) Periodically compares and syncs replicas
Conflict resolution Last-write-wins timestamps, vector clocks, CRDTs, application merge logic

Tunable Consistency

Many systems let you choose per operation:

  • Cassandra: consistency levels such as ONE, QUORUM, LOCAL_QUORUM, ALL. With replication factor N, choosing read ® and write (W) levels such that R + W > N makes reads see the latest acknowledged write in normal operation.

  • DynamoDB: eventually consistent reads by default; strongly consistent reads optionally (within a region, at higher cost).

  • MongoDB: read and write concerns, and read preferences (primary vs secondaries).

Where It Is Acceptable

  • Social media likes and view counts.

  • Product catalogues and recommendations.

  • Activity feeds, analytics, caches.

  • Shopping carts (with merge logic).

Where It Is Not

  • Account balances and payments.

  • Inventory reservations that must not oversell.

  • Unique constraints such as usernames.

Use strong consistency, transactions, or a single-writer design for these.

Handling It in Applications

  • Read-your-writes: route a user’s reads to the primary or wait for replication after their own write.

  • Idempotent operations and version numbers to handle duplicates and reordering.

  • UI design: show pending states or optimistic updates.

Relation to CAP

During a network partition, a system must choose between consistency and availability. Eventually consistent designs choose availability. Even without partitions, the PACELC view notes a trade-off between latency and consistency.

Interview Tip

Define eventual consistency precisely (convergence when updates stop), explain the mechanisms (hinted handoff, read repair, anti-entropy) and tunable consistency with R + W > N. Giving examples of data where it is and is not acceptable shows good judgement.

3

How does NoSQL data modelling differ from relational data modelling?

Relational modelling starts from entities and relationships, normalizes data to avoid duplication, and relies on joins and flexible SQL to answer any query later. NoSQL modelling starts from access patterns: you design the data so each important query is answered by reading one item, document or partition, which usually means denormalization, embedding related data and duplicating it across structures. Schema rules move largely from the database into the application.

Read full answer

Applies todata modelling for document, key-value and wide-column databases (MongoDB, DynamoDB, Cassandra)

Comparison

Aspect Relational NoSQL
Starting point Entities, normalization Queries and access patterns
Structure Tables with fixed columns Documents, items, partitions, graphs
Relationships Foreign keys and joins Embedding, references, duplicated data, adjacency lists
Duplication Avoided (normal forms) Accepted to make reads fast
Schema Enforced by database Flexible; validation optional or in application
Query flexibility Ad-hoc queries easy Efficient only for designed patterns
Integrity Constraints, transactions Application-enforced, limited transactions
Changing access patterns Add an index or query May require new tables, indexes or data migration

Example: Blog With Posts and Comments

Relational

posts(id, author_id, title, body, created_at)
comments(id, post_id, author_id, text, created_at)
users(id, name)
-- Query: join posts, comments and users

Document (MongoDB)

{
  "_id": "post-101",
  "title": "Scaling Writes",
  "author": {"id": "u7", "name": "Ravi"},
  "comments": [
    {"user": {"id": "u9", "name": "Meera"}, "text": "Great post", "at": "2026-05-02"}
  ],
  "commentCount": 1
}

One read returns the post with author name and comments. The author’s name is duplicated; if it changes, the application updates copies (or accepts temporary staleness).

Wide-column (Cassandra): one table per query.

CREATE TABLE comments_by_post (
  post_id text, created_at timeuuid, user_name text, text text,
  PRIMARY KEY ((post_id), created_at)
);

Key NoSQL Modelling Techniques

  • Embed data that is read together and bounded in size (order with its line items).

  • Reference data that is large, unbounded or shared (comments on a viral post may outgrow one document; MongoDB documents are limited to 16 MB).

  • Denormalize frequently read fields into the documents that need them.

  • Choose partition keys that spread load evenly and group data queried together; avoid hot partitions.

  • Single-table design (DynamoDB): store several entity types in one table with composite keys to serve related queries in one request.

  • Precompute aggregates (counts, totals) at write time.

Process

  1. List the application’s queries and their frequency, latency and consistency needs.

  2. Design keys, documents or tables to answer each with minimal reads.

  3. Add secondary indexes for remaining patterns.

  4. Plan how duplicated data stays in sync (transactions, events, background jobs).

Trade-offs

  • Faster reads and easier scaling, at the cost of more complex writes and duplicated data.

  • New queries may require new structures and backfills.

  • Weaker built-in integrity; the application must enforce rules.

Interview Tip

Say “relational models data, NoSQL models queries”, show a short example of embedding vs normalizing, and explain when to embed vs reference. Mentioning partition key choice and hot partitions shows practical experience.

4

What advantages do NoSQL databases offer for large data volumes?

NoSQL databases handle large data volumes well because most are designed for horizontal scaling: data is partitioned automatically across many commodity nodes, replicated for availability, and accessed through simple, predictable access patterns that avoid expensive joins. Many also offer write-optimized storage engines, flexible schemas for varied data, and tunable consistency for low latency at scale.

Read full answer

Applies todistributed NoSQL databases (Cassandra, ScyllaDB, DynamoDB, MongoDB sharded clusters, HBase, Bigtable)

Key Advantages

1. Horizontal scaling (scale out)

  • Data is split by a partition key across nodes (consistent hashing or range partitioning).

  • Adding nodes increases storage and throughput; many systems rebalance data automatically.

  • Avoids the ceiling of a single large server.

2. High write throughput

  • Many wide-column stores use LSM trees (log-structured merge trees): writes go to a commit log and an in-memory table, then are flushed to sorted files sequentially. This makes writes fast and suits ingest-heavy workloads such as IoT telemetry and event logs.

  • B-tree engines (used by most relational databases and some NoSQL engines) are generally better for read-heavy, update-in-place workloads.

3. Built-in replication and availability

  • Data replicated across nodes, racks and data centres.

  • Many systems keep serving requests when nodes fail.

  • Multi-region replication for global applications.

4. Predictable performance at scale

  • Queries designed around keys or partitions touch a small amount of data, so latency stays stable as the dataset grows.

  • No large joins across tables.

5. Flexible schema

  • Semi-structured and evolving data (events with different attributes, product catalogues) can be stored without migrations for every change.

6. Tunable consistency

  • Choose per operation between strong and eventual consistency to balance latency, availability and correctness.

7. Managed and serverless options

  • Services such as DynamoDB, Bigtable, Cosmos DB and MongoDB Atlas handle partitioning, scaling and replication, reducing operations work.

Example

An IoT platform stores readings from 2 million sensors every 10 seconds, which is about 200,000 writes per second. A wide-column table partitioned by (sensor_id, day) spreads writes across a cluster; each query for one sensor’s day of readings reads a single partition. Adding nodes increases capacity as more sensors are deployed.

Trade-offs and Limits

Advantage Cost
Horizontal scale Must design partition keys carefully; hot partitions limit throughput
No joins Denormalization and duplicated data
Eventual consistency options Stale reads, conflict handling
Flexible schema Application must handle multiple data shapes
Write-optimized LSM Compaction overhead, read amplification

Relational databases also scale further than often assumed (read replicas, partitioning, distributed SQL such as CockroachDB, Spanner or YugabyteDB), so NoSQL is not the only option for large data.

Interview Tip

Highlight horizontal partitioning, replication, write-optimized storage and access-pattern-driven design, and give a rough throughput example. Interviewers value mentioning hot partitions and the fact that distributed SQL databases are also an option.

5

When should you choose a NoSQL database over a relational one?

Choose a NoSQL database when your workload has well-known, simple access patterns at very large scale, needs horizontal write scaling or multi-region availability, stores semi-structured or rapidly changing data, or is centred on relationships (graph) or ultra-low-latency key lookups. Choose a relational database when you need complex queries and joins, strong integrity constraints and multi-entity ACID transactions, which is the case for many business applications.

Read full answer

Applies todatabase selection in system design

Signs NoSQL Fits

Requirement Suitable NoSQL type Example
Massive write throughput, time-ordered data Wide-column IoT telemetry, event logs, messaging history
Simple key lookups with sub-millisecond latency Key-value Sessions, caching, rate limiting, leaderboards
Self-contained entities with varied attributes Document Product catalogues, CMS content, user profiles
Deep relationship traversal Graph Fraud detection, recommendations, social networks
Global distribution with local writes Multi-region NoSQL (DynamoDB global tables, Cassandra, Cosmos DB) Gaming profiles, global carts
Predictable latency at any scale with managed scaling Managed NoSQL Serverless back ends

Signs Relational Fits Better

  • Complex queries and reporting across many entities.

  • Strong consistency and transactions across multiple records (payments, ledgers, inventory).

  • Integrity constraints: foreign keys, uniqueness, check constraints.

  • Evolving and unknown query needs: SQL handles new questions without redesign.

  • Moderate scale that a single primary with replicas can handle, which covers many applications.

Decision Questions

  1. What are the main queries, and are they known in advance?

  2. What are the read/write volumes and growth expectations?

  3. What consistency does each operation need?

  4. How related is the data, and do you need joins?

  5. Do you need multi-region writes?

  6. What skills and operational capacity does the team have?

Example

An online game:

  • Player accounts and purchases: relational (PostgreSQL), because payments need transactions and auditing.

  • Player session state and leaderboards: Redis sorted sets for fast reads and updates.

  • Match event history: Cassandra, partitioned by (match_id), handling heavy writes.

  • Friend graph and recommendations: a graph database or adjacency lists, depending on traversal depth.

This polyglot persistence uses each store for what it does best, at the cost of more operational complexity and data synchronization.

Common Mistakes

  • Choosing NoSQL “for scale” before there is a scale problem, then rebuilding joins and transactions in application code.

  • Designing NoSQL tables like relational ones, leading to scans and poor performance.

  • Assuming NoSQL means no transactions: MongoDB supports multi-document ACID transactions and DynamoDB supports TransactWriteItems, though with limits and extra cost.

  • Assuming relational databases cannot scale: replicas, partitioning, caching and distributed SQL go a long way.

Trade-offs

Choose NoSQL Accept
Horizontal scale, flexible schema, low latency for designed queries Denormalization, limited ad-hoc queries, more application-level integrity logic

Interview Tip

Do not answer with a blanket rule. Walk through access patterns, scale, consistency and relationships, then pick per dataset. Many strong candidates say “relational by default, NoSQL where a specific requirement demands it” and justify each choice.

6

What consistency models do NoSQL databases use, and how do they resolve conflicts?

NoSQL databases offer a range of consistency models, from strong (linearizable) consistency through session guarantees (read-your-writes, monotonic reads), causal consistency, bounded staleness to eventual consistency, often tunable per operation. They support transactions at different scopes (single item, single partition, or multi-document ACID), and resolve concurrent updates using leader-based ordering, last-write-wins timestamps, version vectors, conditional writes, CRDTs or application-level merge logic.

Read full answer

Applies todistributed NoSQL databases (Cassandra, DynamoDB, MongoDB, Cosmos DB, Riak, Couchbase)

Consistency Models

Model Guarantee Example support
Strong (linearizable) Every read sees the latest committed write MongoDB with majority read/write concerns on the primary (linearizable read concern available); DynamoDB strongly consistent reads; Cosmos DB Strong
Bounded staleness Reads lag by at most K versions or T time Cosmos DB
Session Within a client session: read-your-writes, monotonic reads Cosmos DB Session (default); MongoDB causally consistent sessions
Causal Causally related operations seen in order MongoDB causal consistency
Consistent prefix Reads never see out-of-order writes Cosmos DB
Eventual Replicas converge if updates stop Cassandra ONE, DynamoDB default reads

Cassandra provides tunable consistency per query (ONE, QUORUM, LOCAL_QUORUM, ALL). With replication factor N, read level R and write level W, R + W > N gives overlap so reads see the latest acknowledged write under normal operation.

Transactions in NoSQL

  • Single-item atomicity: nearly all NoSQL stores guarantee atomic updates of one document or item.

  • Conditional writes / compare-and-set: DynamoDB condition expressions; Cassandra lightweight transactions (IF NOT EXISTS, IF version = 3) using Paxos.

  • Multi-item ACID transactions:

  • MongoDB: multi-document transactions on replica sets (since 4.0) and sharded clusters (since 4.2).

  • DynamoDB: TransactWriteItems and TransactGetItems across up to 100 items.

  • Cosmos DB: transactional batches within one logical partition.

  • Transactions are typically more expensive (latency, throughput cost) and limited in scope, so data models still aim to keep related updates within one item or partition.

Conflict Resolution Strategies

Strategy How it works Trade-off
Single leader per partition All writes for a key go through one primary, which orders them No conflicts, but failover and leader latency
Last-write-wins (LWW) Highest timestamp wins (Cassandra cells, DynamoDB global tables) Simple, but concurrent updates can be silently lost; depends on clocks
Version vectors / vector clocks Detect concurrent versions (siblings) and return them for resolution Accurate detection, application must merge (Riak)
Optimistic concurrency Write only if version matches (IF version = n) Prevents lost updates; caller retries
CRDTs Data types that merge automatically (counters, sets) Limited to suitable data types
Application merge logic Custom rules (union of cart items) Most flexible, most work

Example: Shopping Cart in Two Regions

A user adds “book” in region A and “pen” in region B during a network delay.

  • LWW: one addition may be lost.

  • Set CRDT or merge logic: the result contains both items.

  • Strong consistency with a single home region: both writes go to the same leader, but writes from the far region are slower.

Choosing

  • Money, inventory, uniqueness: strong consistency or conditional writes and transactions.

  • Social content, analytics: eventual consistency.

  • User-facing apps: session consistency is often the best balance.

Interview Tip

List models from strong to eventual with real database examples, explain R + W > N, and compare LWW, vector clocks, conditional writes and CRDTs for conflicts. Stating that modern NoSQL databases support transactions, with scope and cost limits, corrects a common misconception.

8

How does a key-value store work, and what is a typical use case?

A key-value store saves data as pairs of a unique key and a value, where the database treats the value as mostly opaque. Clients put, get and delete values by key, and the store finds the data directly using a hash table or partitioned index, giving very fast lookups, often under a millisecond. A typical use case is session storage or caching, for example storing a logged-in user’s session under session:<id>.

Read full answer

Applies tokey-value databases (Redis, Valkey, Memcached, Amazon DynamoDB, etcd, Riak, RocksDB as an embedded engine)

How It Works

Basic operations

  • PUT(key, value) / SET

  • GET(key)

  • DELETE(key)

  • Often extras: TTL expiry, atomic increment, compare-and-set.

Inside a single node

  • In-memory stores such as Redis keep data in RAM with a hash table, giving lookups in constant time on average.

  • Persistent engines (RocksDB, DynamoDB’s storage) use structures such as LSM trees or B-trees on disk.

Across a cluster

  1. The key is hashed to decide which partition or node owns it (consistent hashing in Dynamo-style systems; Redis Cluster uses 16,384 hash slots).

  2. The request goes to that node (directly or through a router).

  3. Data is replicated to other nodes for availability.

Example: Session Store With Redis

SET session:7f3c9a '{"userId": 42, "roles": ["customer"], "cartItems": 3}' EX 1800
GET session:7f3c9a
EXPIRE session:7f3c9a 1800
DEL session:7f3c9a
  • Each web server reads the session by ID on every request, in well under a millisecond.

  • The 30-minute TTL (EX 1800) removes idle sessions automatically.

  • Web servers stay stateless and can scale horizontally.

Other Common Use Cases

Use case Example key
Caching database or API results product:1001
Rate limiting ratelimit:user42:2026-05-01T10:15 with an atomic increment and TTL
Feature flags and configuration flag:new-checkout
Leaderboards (Redis sorted sets) leaderboard:weekly
Shopping carts cart:user42
Distributed locks (with care) lock:invoice-run
Idempotency keys idem:payment:abc123

Strengths

  • Very low latency and high throughput.

  • Simple API and data model.

  • Easy horizontal scaling by partitioning keys.

Limitations

  • Queries only by key: no searching by value fields unless the store offers secondary indexes (DynamoDB does; plain Redis does not, though modules add search).

  • No joins and limited relationships.

  • Value size limits and performance problems with very large values (“big keys”).

  • Memory cost for in-memory stores.

  • Durability depends on configuration (Redis persistence via RDB snapshots and AOF logs; Memcached has none).

Design Tips

  • Use clear, namespaced key patterns (user:42:profile).

  • Always set TTLs for cache and session data.

  • Avoid hot keys that concentrate traffic on one node; shard or replicate them.

  • Plan cache invalidation when used in front of a database.

Interview Tip

Explain hashing to partitions, the get/put/delete API, and a concrete session or cache example with TTLs. Interviewers often follow up with “What if you need to query by a value?”, so mention secondary indexes or choosing a document store instead.

9

How do you scale key-value stores for high demand or large data?

Key-value stores scale mainly by partitioning (sharding) keys across many nodes with consistent hashing or hash slots, replicating each partition for read capacity and availability, and designing keys to avoid hot spots. Additional techniques include client-side or near caching, read replicas, pipelining and batching, tiered storage for large datasets, and autoscaling in managed services such as DynamoDB.

Read full answer

Applies toRedis / Valkey Cluster, Memcached, DynamoDB, Riak, etcd (limited scale), and RocksDB-based stores

1. Partitioning (Sharding)

  • Consistent hashing: keys are mapped to a ring of nodes; adding a node moves only a fraction of keys. Virtual nodes spread load evenly.

  • Hash slots: Redis Cluster divides the key space into 16,384 slots distributed across primaries; slots can be moved to rebalance.

  • Managed partitioning: DynamoDB splits partitions automatically as data and throughput grow.

2. Replication

  • Primary-replica: replicas serve reads and take over on failure (Redis Sentinel or Cluster failover).

  • Leaderless replication with quorums in Dynamo-style systems.

  • Trade-off: asynchronous replicas may return stale data.

3. Avoid Hot Keys and Hot Partitions

A single popular key (for example a celebrity’s profile or a global counter) can overload one node regardless of cluster size.

Technique Example
Key salting / sharded counters Split views:video123 into views:video123:0..15; sum when reading
Local caching Cache hot reads in application memory for a few seconds
Read replicas Spread reads of hot keys across replicas
Write batching Aggregate increments in memory, flush periodically
Better partition keys DynamoDB: high-cardinality keys instead of status or date alone

4. Improve Client Efficiency

  • Pipelining and batch operations (MGET, MSET, DynamoDB BatchGetItem) to cut round trips.

  • Connection pooling.

  • Keep values small; avoid “big keys” (huge lists or hashes) that block a node.

5. Manage Memory and Data Size

  • TTL and eviction policies (LRU or LFU) for caches.

  • Compression of values.

  • Tiered storage: keep hot data in memory and colder data on SSD (for example Redis on Flash options, or moving cold data to a disk-based store).

  • Use a disk-based key-value store (DynamoDB, RocksDB-based systems) when data far exceeds affordable RAM.

6. Managed Capacity Features

  • DynamoDB on-demand capacity or auto scaling of provisioned capacity.

  • DynamoDB Accelerator (DAX) as an in-memory cache for microsecond reads.

  • Global tables for multi-region reads and writes.

7. Multi-Region and Geo-Distribution

  • Replicate data closer to users; accept eventual consistency or route writes to a home region.

Example: Scaling a Session Store

  • Start: one Redis primary with one replica, 20 GB of sessions.

  • Growth to 200 GB and 300,000 operations per second: move to Redis Cluster with 10 primaries, each with a replica, keys spread across hash slots.

  • Hot key issue from a shared “site config” key: cache it in application memory with a 10-second refresh.

  • Result: load spread evenly; one node’s failure triggers replica promotion with minimal disruption.

Trade-offs

  • Multi-key operations across partitions are limited (Redis Cluster requires keys in one slot, using hash tags like {user42}).

  • Rebalancing moves data and temporarily increases load.

  • Replication lag affects consistency.

  • More nodes increase cost and operational complexity.

Interview Tip

Cover partitioning, replication and hot-key mitigation as the core, then client efficiency and memory management. Mentioning Redis hash slots, sharded counters and DynamoDB partition key design shows practical experience.

10

What are the drawbacks of key-value stores compared to other NoSQL types?

Key-value stores are extremely fast for lookups by key, but they cannot efficiently query by value contents, offer few or no secondary indexes, joins or aggregations, provide limited support for relationships and multi-key transactions, and push data structure and integrity rules into the application. In-memory stores add memory cost and durability trade-offs. Document, wide-column and graph databases handle richer queries better.

Read full answer

Applies tokey-value stores (Redis/Valkey, Memcached, DynamoDB used as pure key-value, Riak KV)

Main Drawbacks

Drawback Why it matters Better alternative for that need
Access only by key Finding “all orders over 100” requires scanning every value Document store with secondary indexes
Opaque values The database cannot validate, index or partially update fields (except in stores that understand the value) Document store
No joins or relationships Related data must be fetched in multiple calls or duplicated Document embedding or graph database
Limited range and sorted queries Hash partitioning scatters adjacent keys Wide-column store with clustering columns
Limited aggregations Counting or summing over many keys needs application code Document aggregation pipelines, wide-column with precomputed tables, analytics stores
Multi-key atomicity Often limited to keys on the same node or slot Document stores with multi-document transactions
Memory cost (in-memory stores) RAM is much more expensive than SSD per GB Disk-based stores, tiered storage
Durability trade-offs Memcached has no persistence; Redis persistence settings can lose recent writes Disk-based databases with synchronous replication
Large values Large values slow network transfers and block single-threaded processing Split data or use object storage
Schema management Application must track value formats and versions Document stores with schema validation

Example

Storing orders as order:<id> → JSON value in Redis works for “get order 123”. But the request “show customer 42’s orders from last month, sorted by total” needs either:

  • A manually maintained secondary structure (a sorted set orders_by_customer:42 with scores), which the application must keep in sync, or

  • A document database with an index on {customerId: 1, createdAt: -1}.

Nuances

  • Redis is more than a plain key-value store: it offers lists, sets, sorted sets, hashes, streams and modules (search, JSON), which mitigate some limits but still require query-specific design.

  • DynamoDB supports sort keys, secondary indexes and transactions, blurring the line with document stores; it still requires designing around known access patterns.

When the Drawbacks Do Not Matter

  • Caches, sessions, rate limits, feature flags, idempotency keys.

  • Any workload where every access is by a known key.

Interview Tip

Contrast key-only access with the richer querying of document, wide-column and graph stores, and give an example query a key-value store cannot answer efficiently. Mentioning that Redis data structures and DynamoDB indexes partly address these limits shows nuance.

11

When is a key-value store not the best fit?

A key-value store is a poor fit when the application needs to query data by its contents, run ad-hoc or analytical queries, follow relationships between records, or update many related records atomically. A typical example is a reporting and order-management system where staff search orders by customer, date range, status and product, and finance needs totals by month.

Read full answer

Applies todatabase selection (Redis, Memcached, plain key-value use of DynamoDB vs document, relational and graph databases)

Example Scenario: Order Management Back Office

Requirements:

  • Search orders by customer name, email, status, date range and product.

  • Sort and paginate results.

  • Show monthly revenue by region and product category.

  • Update an order, its payment record and inventory in one transaction.

  • Enforce rules such as unique invoice numbers.

With a key-value store (order:<id> → JSON):

  • Every search field needs a manually maintained index structure (sets or sorted sets per field), kept in sync on every write.

  • Combined filters (“status = shipped AND region = South AND last 30 days”) require intersecting several structures in application code.

  • Revenue reports require reading all orders.

  • Multi-record atomic updates are limited (Redis transactions apply only to keys on one node or slot in a cluster, and do not roll back on errors).

A relational database (PostgreSQL) with indexes and SQL, or a document database with compound indexes and aggregation pipelines, handles this directly. Reporting can be offloaded to a data warehouse.

Other Poor-Fit Scenarios

Scenario Why key-value struggles Better fit
Social network friend-of-friend queries Multi-hop traversals need many lookups Graph database
Product search with text relevance No full-text search Search engine (Elasticsearch/OpenSearch)
Financial ledger with strict integrity Constraints and multi-entity ACID transactions needed Relational database
Time-range analytics on events Range scans and aggregations Wide-column or time-series store, analytics warehouse
Large binary files Big values hurt performance Object storage (S3) with metadata in a database
Data larger than RAM in an in-memory store Memory cost and eviction Disk-based database

How to Recognize the Mismatch

  • You keep adding secondary index structures by hand.

  • Queries require scanning keys (SCAN over millions of entries).

  • Business logic depends on joins or cross-record constraints.

  • Product managers ask for new filters every month.

Using Key-Value Stores Alongside Others

Key-value stores remain excellent next to a primary database: caching order details, storing sessions, rate limiting search requests. The mistake is using one as the system of record for data that needs rich queries.

Interview Tip

Give a concrete scenario with multi-attribute search, reporting and transactions, explain why key-only access breaks down, and name better alternatives. Interviewers like candidates who suggest keeping the key-value store as a cache rather than discarding it entirely.

12

How does a NoSQL document differ from a relational table row?

A relational row is a flat record with a fixed set of columns defined by the table schema; related data lives in other tables linked by foreign keys and joined at query time. A document (usually JSON or BSON) is a self-contained, hierarchical record that can contain nested objects and arrays, can have different fields from other documents in the same collection, and typically holds related data embedded so it can be read in one operation.

Read full answer

Applies todocument databases (MongoDB, Couchbase, Amazon DocumentDB, Firestore, Cosmos DB) compared with relational databases (PostgreSQL, MySQL, SQL Server)

Comparison

Aspect Relational row Document
Structure Flat columns Nested objects and arrays
Schema Enforced by table definition Flexible; optional schema validation (MongoDB $jsonSchema)
Field variation Same columns for every row (NULLs for missing values) Different documents can have different fields
Related data Separate tables, foreign keys, joins Embedded sub-documents or references
Atomic unit Row (transactions can span many rows) Document (single-document updates are atomic; multi-document transactions available in many systems)
Typical retrieval Join several tables Read one document
Size limits Row size limits per database Per-document limits (for example 16 MB in MongoDB)
Identity Primary key column _id field or document key

Example: Customer Order

Relational rows

orders:       (order_id=501, customer_id=42, status='shipped', total=129.00)
order_items:  (order_id=501, product_id=7, qty=2, price=40.00)
              (order_id=501, product_id=9, qty=1, price=49.00)
customers:    (customer_id=42, name='Asha Rao')

Document

{
  "_id": 501,
  "customer": {"id": 42, "name": "Asha Rao"},
  "status": "shipped",
  "items": [
    {"productId": 7, "qty": 2, "price": 40.00},
    {"productId": 9, "qty": 1, "price": 49.00}
  ],
  "total": 129.00,
  "shipping": {"city": "Pune", "carrier": "BlueDart"}
}

The document maps directly to the application object; the relational version needs a join to assemble the same view.

Implications

Benefits of documents

  • One read for the whole entity: good latency for entity-centric access.

  • Natural fit with object-oriented and JSON-based applications.

  • Easy to add fields without migrations.

  • Sharding by document key is straightforward.

Costs of documents

  • Duplicated data (customer name inside each order) must be kept in sync or accepted as a snapshot.

  • Unbounded arrays (all comments on a post) can make documents grow too large; use references instead.

  • Cross-document queries and joins are less efficient (MongoDB has $lookup, but it is not a substitute for relational design).

  • Schema discipline moves into the application.

Choosing Embedding vs Referencing

  • Embed when data is read together, belongs to the parent, and is bounded (order items, addresses).

  • Reference when data is shared, large, unbounded or updated independently (product details, comments).

Interview Tip

Contrast flat, fixed-schema rows with nested, flexible documents using a short example, then discuss embedding vs referencing and atomicity. Mentioning document size limits and unbounded arrays shows practical modelling experience.

13

How does indexing work in document databases?

Document databases index fields inside documents, including nested fields and array elements, using structures such as B-trees (MongoDB, Couchbase GSI) so queries can find matching documents without scanning the whole collection. Common index types include single-field, compound, multikey (array), text, geospatial, TTL, partial, sparse and wildcard indexes. As with any database, indexes speed reads at the cost of slower writes and extra storage.

Read full answer

Applies todocument databases (MongoDB in examples; similar ideas in Couchbase, Amazon DocumentDB, Cosmos DB and Firestore)

How an Index Works

  • Every collection has a default index on its identifier (_id in MongoDB).

  • A secondary index stores sorted field values with pointers to documents.

  • The query planner chooses an index that matches the filter and sort, reads only matching entries, then fetches the documents (or answers directly from the index if it covers the query).

Index Types (MongoDB Examples)

Index type Example Use
Single field {email: 1} Lookup by email
Compound {customerId: 1, createdAt: -1} Customer’s orders, newest first
Multikey {tags: 1} on an array field Find documents containing a tag
Nested field {"address.city": 1} Query embedded objects
Text {description: "text"} Basic full-text search
Geospatial {location: "2dsphere"} Nearby stores
TTL {createdAt: 1}, {expireAfterSeconds: 86400} Automatically delete old sessions or logs
Partial Index only {status: "active"} documents Smaller, focused index
Unique {email: 1}, {unique: true} Enforce uniqueness
Wildcard {"attributes.$**": 1} Arbitrary attribute keys in flexible schemas
Hashed {userId: "hashed"} Hashed shard keys

Example

db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1 })

db.orders.find(
  { customerId: 42, status: "shipped" }
).sort({ createdAt: -1 }).limit(20)

The compound index matches the equality filters (customerId, status) followed by the sort field (createdAt), so MongoDB can return the latest 20 shipped orders without an in-memory sort.

Compound Index Design: ESR Rule

For compound indexes in MongoDB, a common guideline is Equality, Sort, Range: put fields tested for equality first, then sort fields, then range filters (such as price > 100).

Checking Index Use

db.orders.find({ customerId: 42 }).explain("executionStats")

Look for IXSCAN (index scan) rather than COLLSCAN (collection scan), and compare documents examined with documents returned.

Indexes in Sharded Clusters

  • Queries that include the shard key go to one shard.

  • Queries on other indexed fields may be sent to all shards (scatter-gather), each using its local index, which is slower at scale.

Trade-offs

  • Write overhead: every insert or update modifies all relevant indexes.

  • Memory: indexes perform best when the working set fits in RAM.

  • Multikey indexes on large arrays create many entries.

  • Too many indexes slow writes; unused indexes should be removed (MongoDB $indexStats helps find them).

Interview Tip

Describe B-tree secondary indexes on nested and array fields, list key index types, and show a compound index matched to a query with the ESR rule. Mentioning explain() and the write cost of indexes shows hands-on experience.

14

What is an example of a query in a document database?

In MongoDB, a typical query filters documents by field values, including nested fields and arrays, then sorts, limits and projects the results. For example, “find the 10 most recent shipped orders over 100 for customers in Pune, returning only the order ID, total and date” is expressed with find(). Grouping and totals use the aggregation pipeline.

Read full answer

Applies toMongoDB query language and aggregation pipeline (Couchbase and Cosmos DB offer SQL-like alternatives, such as SQL++ and the Cosmos DB NoSQL query language)

Sample Document

{
  "_id": "ord-501",
  "customer": {"id": 42, "name": "Asha Rao", "city": "Pune"},
  "status": "shipped",
  "items": [
    {"sku": "SHOE-7", "qty": 2, "price": 40},
    {"sku": "SOCK-1", "qty": 3, "price": 5}
  ],
  "total": 95,
  "createdAt": {"$date": "2026-04-28T10:15:00Z"}
}

Example 1: Filter, Sort, Limit, Project

db.orders.find(
  {
    status: "shipped",
    total: { $gt: 100 },
    "customer.city": "Pune"
  },
  { _id: 1, total: 1, createdAt: 1 }
).sort({ createdAt: -1 }).limit(10)
  • "customer.city" queries a nested field.

  • $gt is a comparison operator.

  • The second argument is a projection returning only selected fields.

A supporting index: db.orders.createIndex({ status: 1, "customer.city": 1, createdAt: -1 }).

Example 2: Query Inside an Array

Find orders containing at least 2 units of SHOE-7:

db.orders.find({
  items: { $elemMatch: { sku: "SHOE-7", qty: { $gte: 2 } } }
})

$elemMatch ensures both conditions apply to the same array element.

Example 3: Aggregation (Revenue by City)

db.orders.aggregate([
  { $match: { status: "shipped", createdAt: { $gte: ISODate("2026-04-01") } } },
  { $group: { _id: "$customer.city", revenue: { $sum: "$total" }, orders: { $sum: 1 } } },
  { $sort: { revenue: -1 } },
  { $limit: 5 }
])

The pipeline filters, groups, sorts and limits, similar to WHERE, GROUP BY, ORDER BY and LIMIT in SQL.

Example 4: Update a Nested Field Atomically

db.orders.updateOne(
  { _id: "ord-501", status: "shipped" },
  { $set: { status: "delivered", deliveredAt: new Date() } }
)

Single-document updates are atomic, and the status condition prevents updating an order in an unexpected state.

SQL Equivalent of Example 1

SELECT id, total, created_at
FROM orders JOIN customers ON customers.id = orders.customer_id
WHERE status = 'shipped' AND total > 100 AND customers.city = 'Pune'
ORDER BY created_at DESC
LIMIT 10;

The document version needs no join because the customer’s city is embedded (as a snapshot at order time).

Performance Notes

  • Match the query to an index; check with .explain("executionStats").

  • Put $match early in aggregation pipelines to reduce documents processed.

  • Joins with $lookup are possible but more expensive; model data so frequent queries avoid them.

Interview Tip

Show a find() with a nested-field filter, sort, limit and projection, then an aggregation example. Mentioning $elemMatch for arrays and the index that supports the query shows practical depth.

15

What is a typical application for a document database?

A typical application is a product catalogue for an e-commerce site. Products have different attributes by category (shoes have sizes and colours, laptops have CPU and RAM), are read far more often than written, and are usually displayed as one self-contained entity. A document database stores each product as a JSON-like document with nested attributes, variants and media, allowing fast reads, flexible schema and indexes on the fields customers filter by.

Read full answer

Applies todocument databases (MongoDB, Couchbase, Amazon DocumentDB, Firestore, Cosmos DB)

Why It Fits

Requirement How a document database helps
Varied attributes per category Each document holds only the fields it needs; no wide tables full of NULLs or entity-attribute-value designs
Product page shows everything at once Variants, specs, images and pricing embedded in one document: one read
Frequent schema changes from merchandising New fields added without migrations
Filtering by attributes Secondary, compound and wildcard indexes on fields such as category, brand, attributes.size
High read traffic Replica set members and caching scale reads; sharding by product ID scales data
JSON-native APIs Documents map directly to API responses

Example Document

{
  "_id": "sku-RUN-200",
  "name": "Trail Runner 200",
  "category": "shoes",
  "brand": "Stride",
  "price": {"amount": 7499, "currency": "INR"},
  "attributes": {"gender": "men", "drop_mm": 6, "waterproof": true},
  "variants": [
    {"size": 8, "color": "black", "stock": 14},
    {"size": 9, "color": "black", "stock": 0}
  ],
  "images": ["run200-front.jpg", "run200-side.jpg"],
  "rating": {"avg": 4.4, "count": 312}
}

Example Query

db.products.find({
  category: "shoes",
  "attributes.waterproof": true,
  variants: { $elemMatch: { size: 9, stock: { $gt: 0 } } }
}).sort({ "rating.avg": -1 }).limit(20)

Architecture Around It

Admin tools → Catalogue service → Document DB (system of record) Change stream → Search index (Elasticsearch/OpenSearch) for full-text search and facets Storefront → CDN/cache → Catalogue API

  • The document database stores products.

  • A search engine handles relevance-ranked text search and faceting.

  • Prices or stock that change rapidly may live in separate services and be merged at read time.

Other Typical Applications

  • Content management systems: articles with varied blocks, metadata and tags.

  • User profiles and preferences.

  • Mobile and web app back ends (Firestore, Realm/Atlas Device Sync).

  • Event and log storage with varied payloads.

  • Configuration and metadata stores.

Trade-offs and Cautions

  • Inventory and orders often need stronger transactional guarantees; use multi-document transactions carefully or a relational database for orders and payments.

  • Duplicated data (brand names, category labels) must be kept in sync.

  • Reporting across products is better done in a warehouse.

  • Avoid unbounded arrays (all reviews inside the product document); store reviews in a separate collection.

Interview Tip

Pick one application, explain which characteristics make documents a good fit (varied attributes, entity-centric reads, flexible schema), and show a sample document and query. Pointing out what you would keep elsewhere, such as orders or search, shows balanced judgement.

16

How do document databases handle schema changes and migration?

Document databases do not require a fixed schema, so new fields can be added without altering a table, and documents with old and new shapes can coexist. Schema changes are therefore handled mainly in the application: by versioning documents, writing code that tolerates multiple versions, migrating data lazily on read or write or with background batch migrations, and optionally enforcing rules with schema validation. The schema still exists; it just lives in the application and data contracts.

Read full answer

Applies todocument databases (MongoDB, Couchbase, Firestore, Cosmos DB) and ODMs such as Mongoose

Strategies

1. Additive changes (easiest)

  • Add new optional fields; old documents simply lack them.

  • Code uses defaults when a field is missing.

2. Schema version field

{"_id": "u42", "schemaVersion": 2, "name": {"first": "Asha", "last": "Rao"}}

The application knows how to read version 1 ("name": "Asha Rao") and version 2.

3. Lazy (on-read or on-write) migration

  • When a document is read or updated, the application converts it to the latest version and saves it.

  • Spreads migration cost over time; rarely accessed documents may stay old for a long time.

4. Background batch migration

  • A job updates documents in batches, with throttling to protect production load.

db.users.updateMany(
  { schemaVersion: 1 },
  [ { $set: {
      name: {
        first: { $arrayElemAt: [ { $split: ["$name", " "] }, 0 ] },
        last:  { $arrayElemAt: [ { $split: ["$name", " "] }, 1 ] }
      },
      schemaVersion: 2
  } } ]
)

This uses an update with an aggregation pipeline (MongoDB 4.2+). For very large collections, run it in batches by _id ranges.

5. Expand and contract

  1. Expand: write both old and new fields; readers accept both.

  2. Migrate: backfill existing documents.

  3. Switch readers to the new field.

  4. Contract: stop writing the old field and remove it from documents.

This works safely with rolling deployments where old and new application versions run together.

6. Schema validation

db.runCommand({
  collMod: "users",
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["email", "schemaVersion"],
    properties: { email: { bsonType: "string" } }
  } },
  validationLevel: "moderate"
})

validationLevel: "moderate" applies rules to inserts and to updates of documents that already satisfy the validator, easing transitions.

Index Changes

  • Create new indexes in the background (MongoDB builds indexes without blocking reads and writes for most of the build in recent versions).

  • Drop unused indexes after the code no longer relies on them.

Practical Tips

  • Keep migration scripts in version control, using tools such as migrate-mongo or Mongock.

  • Make migrations idempotent and resumable.

  • Test with copies of production data.

  • Monitor for documents still on old versions.

  • Use ODM schemas (Mongoose, Spring Data) to centralize structure in code.

Trade-offs

Benefit Cost
No downtime for adding fields Code must handle multiple shapes
Gradual migration Mixed versions can persist and complicate queries
Fast iteration Weaker guarantees unless validation is used

Interview Tip

Explain that “schemaless” means the schema moves to the application, then describe schema versioning, lazy and batch migration, and expand-and-contract. Mentioning $jsonSchema validation and idempotent migration scripts shows production experience.

17

How is data structured in a column-family store, and which queries does it suit?

A column-family (wide-column) store organizes data into tables of rows identified by a partition key, where each partition holds many rows sorted by clustering columns, and each row can have many columns. Data for one partition is stored together on the same nodes, in sorted order, so the model excels at lookups by partition key and range scans within a partition, such as “the latest 100 readings for sensor X” or “messages in conversation Y between two dates”. It is designed for very high write throughput at large scale.

Read full answer

Applies toApache Cassandra and ScyllaDB (CQL); Apache HBase and Google Bigtable use a similar row-key and column-family model

Data Structure (Cassandra Terminology)

  • Keyspace: like a database; defines replication.

  • Table: a set of rows with a defined primary key.

  • Partition key: determines which nodes store the data (hashed with consistent hashing).

  • Clustering columns: sort rows within a partition.

  • Columns: values; rows can be sparse.

CREATE TABLE readings_by_sensor (
  sensor_id   text,
  day         date,
  reading_ts  timestamp,
  temperature double,
  humidity    double,
  PRIMARY KEY ((sensor_id, day), reading_ts)
) WITH CLUSTERING ORDER BY (reading_ts DESC);
  • (sensor_id, day) is a composite partition key: one partition per sensor per day, bounding partition size.

  • reading_ts is the clustering column, sorted newest first.

Conceptually:

Partition ("s-17", 2026-05-01):
  10:15:00 → temperature 24.1, humidity 51
  10:14:50 → temperature 24.0, humidity 52
  ...

In HBase/Bigtable, data is a sorted map: row key → column family → column qualifier → timestamped value. Column families are stored separately, and rows are sorted by row key, enabling range scans by key prefix.

Queries It Supports Well

Query Why it is efficient
Get one partition by key Hash points to the owning nodes
Range within a partition (reading_ts > X) Rows are stored sorted by clustering columns
Latest N items Descending clustering order plus LIMIT
High-volume inserts LSM-tree storage appends writes sequentially
SELECT reading_ts, temperature
FROM readings_by_sensor
WHERE sensor_id = 's-17' AND day = '2026-05-01'
  AND reading_ts >= '2026-05-01 09:00:00'
LIMIT 100;

Queries It Does Not Support Well

  • Filtering on non-key columns without an index (Cassandra rejects these unless ALLOW FILTERING is used, which can scan many partitions).

  • Joins and ad-hoc aggregations across partitions.

  • Global sorting across all partitions.

These are solved by query-first modelling: create one table per query pattern, duplicating data (for example readings_by_sensor and alerts_by_site), or by using analytics engines (Spark) for broad queries.

Design Considerations

  • Choose partition keys with high cardinality and even traffic to avoid hot partitions.

  • Bound partition size (time buckets such as day or hour); very large partitions hurt performance (a common guideline is to keep them well under about 100 MB).

  • Writes are cheap; denormalization is normal.

  • Deletes create tombstones; heavy delete patterns can slow reads until compaction.

Interview Tip

Explain partition key vs clustering columns with a time-series example and show which queries are efficient and which are not. Mentioning query-first modelling (one table per query) and bounded partitions shows real Cassandra experience.

19

How do column-family stores partition and distribute data?

Column-family stores partition data by a partition (row) key. Cassandra and ScyllaDB hash the partition key onto a token ring using consistent hashing, so each node owns token ranges and partitions are spread evenly; replicas are placed on additional nodes according to the replication strategy. HBase and Bigtable instead use range partitioning: rows are sorted by row key and split into regions or tablets assigned to servers. The choice of key decides both load balance and which queries are efficient.

Read full answer

Applies toApache Cassandra, ScyllaDB, Apache HBase, Google Bigtable

Hash Partitioning (Cassandra, ScyllaDB)

  1. The partition key is hashed (Murmur3 by default) into a token.

  2. The token falls in a range owned by a node (each node has many virtual node ranges).

  3. With replication factor 3, the data is also stored on the next two nodes clockwise (by token), adjusted by rack and data-centre awareness with NetworkTopologyStrategy.

CREATE KEYSPACE shop WITH replication =
  {'class': 'NetworkTopologyStrategy', 'dc_mumbai': 3, 'dc_singapore': 3};

Effects

  • Even distribution when keys have high cardinality.

  • Adding a node takes over some token ranges; only a fraction of data moves.

  • Range scans across partitions are inefficient because adjacent keys land on different nodes, but range scans within a partition (by clustering columns) are efficient.

Range Partitioning (HBase, Bigtable)

  1. Rows are stored sorted by row key.

  2. The key space is split into regions (HBase) or tablets (Bigtable).

  3. Regions split automatically as they grow and are moved between servers to balance load.

Effects

  • Efficient scans over key ranges (for example all rows with prefix sensor17#2026-05).

  • Risk of hotspots when keys are sequential (timestamps or incrementing IDs), because all new writes go to the last region.

Avoiding Hot Partitions and Hotspots

Problem Technique
Low-cardinality key (e.g. country) Use a higher-cardinality key or composite key
One huge partition (popular user, busy sensor) Add a time bucket: ((sensor_id, day), ts)
Sequential row keys in HBase/Bigtable Salting or hashing a prefix, field promotion, or reversing timestamps
Uneven traffic per key Spread writes across sub-partitions (bucket = hash % N) and query all buckets

Impact on Performance

  • Single-partition queries go to a small set of replicas: fast and predictable.

  • Multi-partition queries require coordinating many nodes: slower, more load.

  • Partition size affects read latency, compaction and repair; bounding partitions keeps performance stable.

  • Replication placement across racks and data centres provides fault tolerance; LOCAL_QUORUM keeps reads and writes within one data centre for low latency.

Example

A ride-sharing app stores trip location pings:

  • Key ((driver_id, hour), ts) distributes drivers across the ring and bounds each partition to one hour of pings.

  • Query “driver 881’s route between 10:00 and 10:30” reads one partition.

  • A global query “all drivers in an area now” is not served by this table; a separate table keyed by geohash cell and time, or a dedicated geospatial store, handles it.

Interview Tip

Distinguish hash partitioning on a token ring (Cassandra) from range partitioning into regions (HBase/Bigtable), explain replica placement, and discuss hot partitions with concrete fixes such as time bucketing and salting. Interviewers value linking key design to which queries are efficient.

20

How is data represented in a graph database?

A graph database represents data as nodes (entities), edges or relationships (connections between entities, with a type and direction), and properties (key-value attributes on both). In the common property graph model, nodes also have labels such as Person or Product. Relationships are stored as first-class data, so queries can traverse connections directly instead of computing joins.

Read full answer

Applies tograph databases (Neo4j, Amazon Neptune, Memgraph, JanusGraph, TigerGraph; query languages Cypher/openCypher, Gremlin, GQL, and SPARQL for RDF)

Property Graph Elements

Element Description Example
Node An entity A person, product, account, device
Label Category of a node (a node can have several) :Person, :Customer
Relationship / edge Directed, typed connection between two nodes (:Person)-[:FOLLOWS]->(:Person)
Relationship type The kind of connection PURCHASED, FRIEND_OF, TRANSFERRED_TO
Properties Key-value attributes on nodes or edges name: "Asha", since: 2024, amount: 5000

Example in Cypher

CREATE (a:Person {name: "Asha", city: "Pune"})
CREATE (r:Person {name: "Ravi"})
CREATE (p:Product {sku: "SHOE-7", name: "Trail Runner"})
CREATE (a)-[:FOLLOWS {since: 2024}]->(r)
CREATE (r)-[:PURCHASED {at: date("2026-04-02"), qty: 1}]->(p)

Query: products bought by people Asha follows.

MATCH (:Person {name: "Asha"})-[:FOLLOWS]->(friend)-[:PURCHASED]->(product)
RETURN product.name, count(friend) AS buyers
ORDER BY buyers DESC

Storage and Index-Free Adjacency

Native graph databases such as Neo4j store each node with direct references to its relationships, an approach called index-free adjacency. Following an edge is a pointer lookup, so traversal cost depends on the portion of the graph visited, not the total size of the database. Other graph databases build on distributed storage (JanusGraph on Cassandra or HBase) and use indexes to find neighbours.

RDF Model (Alternative)

The Resource Description Framework represents data as triples: subject, predicate, object.

<Asha> <follows> <Ravi> .
<Ravi> <purchased> <SHOE-7> .

Queried with SPARQL, RDF is common in knowledge graphs and linked data. Amazon Neptune supports both property graphs and RDF.

Relational Comparison

In a relational database, the same data needs a persons table, a follows(follower_id, followee_id) join table and a purchases table. A three-hop query requires several self-joins, whose cost grows with table sizes. A graph database expresses it as a path pattern.

Modelling Tips

  • Model things as nodes and verbs as relationships.

  • Put properties that describe the connection (date, weight, amount) on the edge.

  • Avoid supernodes (a node with millions of edges, such as a celebrity) on hot paths; use relationship types, time buckets or intermediate nodes to split them.

  • Index node properties used as starting points (CREATE INDEX FOR (p:Person) ON (p.email)).

Trade-offs

  • Excellent for relationship-heavy, multi-hop queries.

  • Less suited to bulk aggregations across all data, simple key lookups at massive scale, or large binary data.

  • Horizontal scaling of graph workloads is harder than for key-value stores because traversals cross partitions.

Interview Tip

Describe nodes, relationships, labels and properties with a small Cypher example, explain index-free adjacency, and mention the RDF triple model as an alternative. Interviewers often follow up on supernodes, so be ready to explain how you would handle them.

21

How does querying a graph database compare with other NoSQL types?

Graph databases are queried with pattern-matching and traversal languages (Cypher, Gremlin, GQL, SPARQL) that start from nodes and follow relationships, making multi-hop and path queries natural and efficient. Other NoSQL types are queried mainly by key (key-value), by document fields (document stores), or by partition key and clustering ranges (wide-column). Those stores struggle with deep relationship queries, while graph databases are not optimized for simple key lookups at massive scale or large analytical scans.

Read full answer

Applies toNoSQL querying (Neo4j Cypher, Apache TinkerPop Gremlin, ISO GQL; Redis/DynamoDB key APIs; MongoDB query language; Cassandra CQL)

Comparison

Aspect Key-value Document Wide-column Graph
Query style GET key Filter on fields, aggregation pipelines SELECT ... WHERE partition_key = ? with clustering ranges Pattern matching and traversals
Relationships None (manual) Embedded or referenced; $lookup joins Denormalized per query table First-class edges
Multi-hop queries Many round trips Multiple queries or expensive lookups Precomputed tables Native and efficient
Ad-hoc queries Very limited Good with indexes Limited (query-first design) Good for relationship questions
Aggregations over all data Not supported Aggregation pipeline Limited; use Spark Possible but not the main strength
Typical latency for its main pattern Sub-millisecond Milliseconds Milliseconds Milliseconds for local traversals

Same Question, Different Stores

“Find friends of friends of user 42 who bought product X.”

Graph (Cypher)

MATCH (u:User {id: 42})-[:FRIEND]-(:User)-[:FRIEND]-(fof:User)-[:BOUGHT]->(:Product {sku: "X"})
WHERE fof.id <> 42
RETURN DISTINCT fof.id

Document store

  1. Read user 42’s document to get friend IDs.

  2. Query all friends’ documents to get their friend IDs.

  3. Query purchases for those IDs and product X.

  4. Deduplicate in application code.

Wide-column store

Maintain precomputed tables such as friends_by_user and buyers_by_product, then intersect in application code; deeper or new patterns need new tables.

Key-value store

Repeated GET calls for each friend list, with all logic in the application.

Graph-Specific Query Capabilities

  • Variable-length paths: -[:FRIEND*1..3]- finds connections up to three hops.

  • Shortest paths: shortestPath() between two nodes.

  • Pattern detection: cycles of money transfers in fraud detection.

  • Graph algorithms (via libraries such as Neo4j Graph Data Science): PageRank, community detection, similarity.

Performance Considerations

  • Graph queries need good starting points (indexed node properties); a query that begins with a full graph scan is slow.

  • Supernodes with millions of edges make traversals expensive.

  • Distributing graphs across machines is harder because traversals cross partitions.

  • For aggregations over billions of records, data warehouses or wide-column stores with analytics engines are better.

Choosing

  • Questions about connections, paths and patterns: graph.

  • Entity-centric reads and flexible attributes: document.

  • Massive time-ordered writes and range reads by key: wide-column.

  • Simple lookups with very low latency: key-value.

Interview Tip

Use a friend-of-friend or fraud example to show how one Cypher pattern replaces several round trips in other stores. Mentioning variable-length paths, the need for indexed starting points and supernode problems shows practical understanding.

22

What real-world problem is a good fit for a graph database?

Fraud detection in financial transactions is a strong fit. Fraud rings hide behind chains of connections: shared devices, phone numbers, addresses, accounts and money transfers. Detecting them means asking questions such as “is this new account connected within three hops to known fraudulent accounts?”, which a graph database answers with fast traversals, while relational or other NoSQL stores would need many joins or round trips.

Read full answer

Applies tograph databases (Neo4j, Amazon Neptune, TigerGraph, Memgraph) in fraud, risk and identity use cases

The Problem

A bank sees fraudulent loan applications. Individually, each application looks normal, but fraudsters reuse a small set of devices, phone numbers, emails and addresses across many synthetic identities, and move money through chains of mule accounts.

Graph Model

  • Nodes: Customer, Account, Device, Phone, Email, Address, Merchant.

  • Relationships: (:Customer)-[:OWNS]->(:Account), (:Customer)-[:USES]->(:Device), (:Customer)-[:HAS_PHONE]->(:Phone), (:Account)-[:TRANSFERRED {amount, at}]->(:Account).

Example Queries

Shared identifiers with known fraudsters

MATCH (new:Customer {id: $applicantId})-[:USES|HAS_PHONE|LIVES_AT*1..2]-(other:Customer)
WHERE other.flaggedFraud = true
RETURN DISTINCT other.id, other.name

Money moving in a cycle (possible laundering)

MATCH path = (a:Account)-[:TRANSFERRED*3..5]->(a)
WHERE all(t IN relationships(path) WHERE t.at > datetime() - duration('P7D'))
RETURN path LIMIT 10

Ring detection with graph algorithms: connected components or community detection to find clusters of customers sharing identifiers.

Why a Graph Database Fits

Need Graph strength
Multi-hop connections (2–5 hops) Native traversal, cost proportional to visited neighbourhood
Flexible patterns that change as fraudsters adapt New queries without redesigning tables
Real-time checks during an application or payment Millisecond traversals from an indexed starting node
Explainability for investigators Paths can be visualized and shown as evidence
Graph analytics Centrality, community detection, similarity scores as ML features

Architecture Sketch

Application events → Stream (Kafka) → Graph loader → Graph DB Loan service → Risk API → Graph traversal query (under 50 ms target) → Risk score Investigators → Graph visualization tool

The graph is usually not the system of record; core banking data stays in relational systems, and the graph is updated from events.

Other Good Fits

  • Recommendations: “people who bought X also bought Y”, collaborative filtering through shared purchases.

  • Social networks: friends of friends, mutual connections, influence.

  • Knowledge graphs: linking entities and concepts for search or AI retrieval.

  • IT network and dependency mapping: impact analysis (“what breaks if this switch fails?”).

  • Supply chain: tracing components through suppliers.

  • Identity and access management: who can access what through nested groups and roles.

Trade-offs

  • Supernodes (for example, a shared public Wi-Fi IP used by thousands) can make traversals slow and noisy; filter or treat them specially.

  • Keeping the graph in sync with source systems adds pipelines.

  • Large-scale distributed graph processing is harder than scaling key-value workloads.

Interview Tip

Choose one problem, describe the nodes and relationships, show one or two traversal queries, and explain why joins would be expensive. Mentioning real-time scoring, supernodes and that the graph complements the system of record shows practical design thinking.

23

What role does an edge play in a graph database?

An edge (also called a relationship) is a connection between two nodes that describes how they are related. In a property graph, every edge has a type (such as FOLLOWS or PURCHASED), a direction (from a start node to an end node), and optionally properties (such as since, amount or weight). Edges are stored as first-class data, which is what allows graph databases to traverse relationships efficiently instead of computing joins at query time.

Read full answer

Applies toproperty graph databases (Neo4j, Amazon Neptune, Memgraph, JanusGraph); in RDF stores the equivalent is the predicate of a triple

Nodes vs Edges

Aspect Node Edge
Represents An entity (person, account, product) A connection or interaction (follows, owns, transferred)
Identity Has an ID and labels Has an ID, a type and two endpoints
Properties Describe the entity Describe the relationship (date, amount, strength)
Can exist alone Yes No: always connects a start and end node

Example

MATCH (a:Account {id: "A1"}), (b:Account {id: "B7"})
CREATE (a)-[:TRANSFERRED {amount: 25000, currency: "INR", at: datetime("2026-05-01T10:15:00")}]->(b)
  • Type: TRANSFERRED

  • Direction: from A1 to B7

  • Properties: amount, currency, time

Roles of Edges

  1. Express meaning: the relationship type carries semantics (MANAGES vs REPORTS_TO).

  2. Enable traversal: queries follow edges from one node to the next: (u)-[:FRIEND*1..3]-(x).

  3. Carry data about the relationship: weights for recommendations, timestamps for temporal queries, amounts for fraud analysis.

  4. Filter paths: queries can restrict by edge type and properties (WHERE t.amount > 10000).

  5. Support graph algorithms: shortest path, PageRank and community detection use edges and their weights.

Direction

  • Edges are stored with a direction, but queries can ignore it: (a)-[:FRIEND]-(b) matches both directions.

  • For symmetric relationships (friendship), store one edge and query without direction rather than creating two.

Modelling Choices

Edge property vs intermediate node

If a relationship has its own rich data or connects to other entities, model it as a node.

  • Simple: (:Person)-[:PURCHASED {at, qty}]->(:Product)

  • Richer: (:Person)-[:PLACED]->(:Order)-[:CONTAINS]->(:Product) when orders have their own payments, shipments and status.

Specific relationship types

Prefer specific types (PURCHASED, VIEWED, WISHLISTED) over a generic INTERACTED {kind: "purchase"}, because traversals can then filter by type efficiently.

Performance Notes

  • In native graph storage, each node keeps references to its edges (index-free adjacency), so following an edge is a direct lookup.

  • Supernodes with millions of edges make traversals expensive; splitting by type or time, or adding intermediate nodes, helps.

  • Edge properties can be indexed in some databases for filtering.

Interview Tip

Define an edge by its type, direction and properties, give a concrete example, and explain that edges make traversals efficient. Discussing when to model a relationship as an intermediate node instead of an edge shows modelling maturity.

24

What replication strategies do NoSQL databases commonly use?

NoSQL databases commonly use three replication strategies: single-leader (primary-secondary) replication, where one node accepts writes for a partition and copies them to followers (MongoDB replica sets, Redis, HBase via HDFS); leaderless (Dynamo-style) replication, where any replica accepts writes and quorums control consistency (Cassandra, ScyllaDB, Riak); and multi-leader / multi-region replication, where several regions accept writes and replicate to each other (DynamoDB global tables, Cosmos DB multi-region writes, Couchbase XDCR). Each balances consistency, availability, latency and conflict handling differently.

Read full answer

Applies todistributed NoSQL databases

1. Single-Leader (Primary-Secondary)

  • All writes for a partition go to the primary, which logs them and replicates to secondaries.

  • Reads can go to the primary (consistent) or secondaries (possibly stale).

  • On primary failure, an election promotes a secondary.

Example: MongoDB replica set

  • One primary, two or more secondaries.

  • Write concern w: "majority" waits until most members acknowledge, protecting against rollback on failover.

Trade-offs: no write conflicts and simple consistency, but write throughput is limited by the primary per shard, and failover causes a brief write pause (seconds).

2. Leaderless (Dynamo-Style)

  • The client or a coordinator sends writes to all N replicas and waits for W acknowledgements; reads query R replicas.

  • If R + W > N, read and write sets overlap, so reads normally see the latest acknowledged write.

  • Mechanisms: hinted handoff, read repair, anti-entropy repair with Merkle trees.

Example: Cassandra

CREATE KEYSPACE app WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
-- query with CONSISTENCY LOCAL_QUORUM (2 of 3 replicas in the local DC)

Trade-offs: high availability and no failover pause, but conflicts are resolved with last-write-wins timestamps by default, and consistency depends on chosen levels.

3. Multi-Leader / Multi-Region

  • Each region accepts writes locally and replicates asynchronously to other regions.

  • Low write latency for global users and regional fault tolerance.

  • Conflicts must be resolved: last-write-wins (DynamoDB global tables), custom resolution (Cosmos DB conflict policies), or CRDTs.

Synchronous vs Asynchronous Replication

Mode Behaviour Trade-off
Synchronous Write acknowledged after replicas confirm Stronger durability and consistency, higher latency
Asynchronous Acknowledged before replicas confirm Low latency, risk of losing recent writes on failure, stale reads
Semi-synchronous / quorum Wait for some replicas Balance between the two

Replica Placement

  • Spread replicas across racks, availability zones and regions so one failure does not lose all copies.

  • Cassandra’s NetworkTopologyStrategy and MongoDB replica set tags support this.

Comparison

Strategy Write availability Consistency Conflicts Examples
Single-leader Paused during failover Strong from primary None MongoDB, Redis, HBase
Leaderless High Tunable (quorums) LWW or versioning Cassandra, ScyllaDB, Riak
Multi-leader Very high, global Eventual across regions Must resolve DynamoDB global tables, Cosmos DB, Couchbase XDCR

Interview Tip

Explain the three strategies, how R + W > N works in leaderless systems, and the synchronous vs asynchronous trade-off. Interviewers often follow up on conflict resolution in multi-region setups, so mention last-write-wins and its risk of losing concurrent updates.

25

What are quorum reads and writes, and how do they affect consistency?

In a replicated database with N replicas of each piece of data, a quorum write succeeds once W replicas acknowledge it, and a quorum read queries R replicas and returns the newest value among them. If R + W > N, every read set overlaps every write set in at least one replica, so reads normally return the latest acknowledged write. Choosing R and W lets you trade consistency against latency and availability.

Read full answer

Applies toleaderless (Dynamo-style) databases such as Cassandra, ScyllaDB and Riak; similar majority ideas appear in MongoDB write/read concerns and consensus systems

The Basic Rule

With N = 3 replicas:

Setting R + W Behaviour
W = 1, R = 1 2 (not > 3) Fastest, highest availability; reads may be stale
W = 2, R = 2 (quorum) 4 > 3 Read and write sets overlap; latest acknowledged write is seen in normal operation; tolerates 1 replica down
W = 3, R = 1 4 > 3 Fast reads; writes fail if any replica is down
W = 1, R = 3 4 > 3 Fast writes; reads fail if any replica is down

A majority quorum is floor(N/2) + 1, so 2 of 3 or 3 of 5.

How a Quorum Read Works

  1. The coordinator sends the read to R replicas (or to all, waiting for R responses).

  2. It compares versions (timestamps) and returns the newest.

  3. If replicas disagree, read repair updates the stale ones.

Cassandra Example

-- Replication factor 3 in each data centre
CONSISTENCY LOCAL_QUORUM;
INSERT INTO accounts_by_id (id, email) VALUES ('u42', 'asha@example.com');
SELECT email FROM accounts_by_id WHERE id = 'u42';

LOCAL_QUORUM requires 2 of 3 replicas in the local data centre, keeping latency low while giving overlap within that data centre.

Impact on Consistency, Latency and Availability

  • Consistency: R + W > N gives read-after-write behaviour under normal conditions.

  • Latency: the operation waits for the slowest of the required R or W replicas; larger quorums mean higher tail latency, and cross-region quorums add tens to hundreds of milliseconds.

  • Availability: with N = 3 and quorum 2, operations survive one replica failure; with ALL, any failure blocks the operation.

Important Caveats

Quorums do not give full linearizability on their own:

  • Concurrent writes are resolved by timestamps (last-write-wins), so one update can be silently overwritten; clock skew can pick the “wrong” winner.

  • Failed writes that reached fewer than W replicas may still persist on some replicas and later appear in reads.

  • Sloppy quorums with hinted handoff (used by some Dynamo-style systems to stay available) may write to nodes outside the usual replica set, weakening the overlap guarantee temporarily.

  • Reads during repair may still see older values in edge cases.

For operations needing true compare-and-set semantics, use lightweight transactions (Cassandra IF conditions, based on Paxos) or a consensus-based database, accepting higher latency.

Choosing Levels

Use case Typical choice
User profile reads after updates LOCAL_QUORUM reads and writes
Metrics or logs Write ONE, read ONE
Critical uniqueness (usernames) Lightweight transaction (IF NOT EXISTS)
Multi-region with local latency LOCAL_QUORUM, accept cross-region eventual consistency

Interview Tip

State R + W > N with an N = 3 example, explain the latency and availability effect, and add the caveats: last-write-wins conflicts and sloppy quorums mean quorums are not full linearizability. That nuance is what interviewers look for.

26

How do NoSQL databases maintain consistency during network partitions?

During network partitions, NoSQL databases follow the choice CAP forces on them: either preserve consistency by refusing some operations on the side that cannot reach a majority, or stay available by accepting operations on both sides and reconciling later. Consistent (CP-leaning) systems use leader election and majority quorums; available (AP-leaning) systems use tunable quorums, hinted handoff, versioning and conflict resolution, then repair replicas when the network heals. Many databases let you choose per operation.

Read full answer

Applies todistributed NoSQL databases (MongoDB, Cassandra, DynamoDB, Cosmos DB, Riak, etcd/ZooKeeper-style consensus stores)

What a Partition Means

Nodes are running but some cannot communicate. For example, a 5-node cluster split into groups of 3 and 2, or two data centres losing their link. The system cannot both accept writes everywhere and guarantee that every read sees the latest write.

CP-Leaning Behaviour: Majority Wins

MongoDB replica sets

  • A primary must be able to reach a majority of voting members.

  • If the primary ends up in the minority, it steps down; the majority side elects a new primary.

  • Writes with w: "majority" succeed only on the majority side.

  • Clients on the minority side cannot write (and should use majority reads to avoid stale data).

  • When the partition heals, writes on the old primary that were not majority-acknowledged are rolled back.

Consensus-based stores (etcd, ZooKeeper, and distributed SQL or NoSQL systems built on Raft or Paxos) behave similarly: only a majority can make progress.

AP-Leaning Behaviour: Accept and Reconcile

Cassandra and Dynamo-style systems

  • With consistency level ONE, writes succeed on any reachable replica on either side.

  • Hinted handoff stores writes for unreachable replicas and replays them later.

  • After healing, read repair and anti-entropy repair (Merkle tree comparisons) bring replicas back in sync.

  • Conflicts are resolved by last-write-wins timestamps (Cassandra), vector clocks with siblings (Riak), or CRDTs.

  • With QUORUM, the minority side cannot meet the quorum and rejects operations, so the system behaves more like CP for those operations.

Multi-region replication (DynamoDB global tables, Cosmos DB multi-region writes)

  • Each region keeps accepting local writes during an inter-region partition.

  • Replication resumes later; conflicting writes are resolved by last-writer-wins or custom policies.

Tunable Choices

Operation Choice during partitions
Payment or inventory reservation Majority quorum or transactions: fail rather than risk inconsistency
Shopping cart Accept writes, merge later (union of items)
Likes and view counts Accept writes; counters or CRDTs merge
User profile update Quorum within the local region

Beyond Partitions: PACELC

Even without partitions, there is a trade-off between latency and consistency: waiting for more replicas or remote regions increases latency. PACELC describes this: under Partition choose Availability or Consistency, Else choose Latency or Consistency.

Application-Level Safeguards

  • Idempotency keys so retried writes do not duplicate effects.

  • Version numbers / conditional writes to prevent lost updates.

  • Compensating actions and reconciliation jobs for business inconsistencies.

  • Clear user messaging when operations are temporarily rejected.

Interview Tip

Explain the CAP choice during partitions correctly (consistency vs availability, not “pick two”), contrast MongoDB’s majority-based behaviour with Cassandra’s hinted handoff and repair, and mention PACELC for the normal-operation trade-off. Giving per-use-case choices shows strong judgement.

27

What sharding strategies do NoSQL databases use, and how do they affect performance?

NoSQL databases shard data mainly by hash-based, range-based, directory (lookup-based) or geographic strategies, often combined with composite keys. The shard key decides how evenly data and traffic spread across nodes and which queries can be answered by a single shard versus a slower scatter-gather across all shards. Good keys give linear scaling; poor keys cause hot shards, large partitions and expensive rebalancing.

Read full answer

Applies toMongoDB sharding, Cassandra/ScyllaDB partitioning, DynamoDB partitions, Redis Cluster, HBase/Bigtable regions, Elasticsearch shards

Strategies

Strategy How it works Strengths Weaknesses Examples
Hash-based Hash of key decides the shard Even distribution, avoids hotspots for sequential keys Range queries across keys hit all shards Cassandra, DynamoDB, Redis Cluster (hash slots), MongoDB hashed shard keys
Range-based Contiguous key ranges per shard Efficient range scans, ordered data Hotspots with sequential keys (timestamps, increasing IDs) HBase, Bigtable, MongoDB ranged shard keys
Directory / lookup A lookup table maps keys or tenants to shards Flexible placement, move tenants individually Lookup service is extra infrastructure and a dependency Custom multi-tenant systems, Vitess-style approaches
Geographic Data placed by region or user location Low latency, data residency compliance Cross-region queries, uneven regional load MongoDB zone sharding, Cosmos DB, Cassandra per-DC replication
Composite keys Combine fields, e.g. (tenant_id, user_id) or (sensor_id, day) Balances distribution and query locality Queries must supply the full key Cassandra composite partition keys

Effect on Performance

Targeted vs scatter-gather queries

  • Queries that include the shard key go to one shard: low latency, scalable.

  • Queries without it fan out to all shards; latency is set by the slowest shard, and load grows with cluster size.

Hot shards

  • Low-cardinality keys (country, status) or skewed traffic (one celebrity user) overload one shard while others sit idle.

  • Fixes: higher-cardinality keys, key salting (user_id#bucket), time bucketing, caching hot reads.

Partition size

  • Very large partitions (all events for one device ever) slow reads, compaction and rebalancing. Bound them with time buckets.

Rebalancing

  • Adding nodes moves data. Consistent hashing with virtual nodes (Cassandra) or slot migration (Redis Cluster) limits movement; MongoDB’s balancer moves chunks between shards in the background, using I/O and network.

Cross-shard operations

  • Joins, aggregations and transactions across shards are slower and more complex; model data so related items share a shard key.

Example: MongoDB Orders Collection

sh.shardCollection("shop.orders", { customerId: "hashed" })
  • Orders spread evenly across shards.

  • “Orders for customer 42” targets one shard.

  • “All orders yesterday” hits every shard; for such queries, add a secondary index (searched on each shard) or use an analytics pipeline.

An alternative compound key { customerId: 1, orderDate: 1 } (ranged) supports customer-plus-date-range queries efficiently on one shard while keeping distribution good, as long as customer IDs are well distributed.

Choosing a Shard Key

  1. High cardinality and even frequency.

  2. Present in the most common queries.

  3. Avoids monotonic increase for range-based sharding.

  4. Groups data that must be updated together.

  5. Hard to change later (MongoDB allows resharding since 5.0, but it is a heavy operation), so test with realistic data.

Interview Tip

Compare hash, range, directory and geographic strategies, then explain targeted vs scatter-gather queries and hot shards with a concrete fix. Interviewers often ask “How would you pick a shard key for X?”, so walk through cardinality, query patterns and monotonic keys.

28

How is load balancing achieved in NoSQL database clusters?

Load balancing in NoSQL clusters happens at several levels: data distribution (hashing or ranges spread partitions evenly across nodes), request routing (smart drivers, coordinator nodes or routers send each request to the right replicas), replica selection (reads spread across replicas, preferring the fastest or closest), and automatic rebalancing when nodes are added or partitions become hot. External load balancers are used less than with stateless services, because requests must reach the nodes that own the data.

Read full answer

Applies toCassandra/ScyllaDB, MongoDB sharded clusters, DynamoDB, Redis Cluster, Elasticsearch/OpenSearch, Couchbase

1. Even Data Distribution

  • Consistent hashing with virtual nodes (Cassandra): each node owns many small token ranges, so data and load spread evenly.

  • Hash slots (Redis Cluster): 16,384 slots distributed across primaries.

  • Chunks and balancer (MongoDB): data split into chunks by shard key; the balancer migrates chunks to even out shards.

  • Adaptive partitioning (DynamoDB): partitions split as data or throughput grows; adaptive capacity shifts throughput to busier partitions.

2. Request Routing

System Routing approach
Cassandra / ScyllaDB Token-aware drivers send requests directly to a replica that owns the data; any node can coordinate
MongoDB mongos routers use cluster metadata to route queries to the right shards
Redis Cluster Cluster-aware clients cache the slot map; MOVED redirects update it
DynamoDB AWS request routers direct calls to partitions transparently
Elasticsearch Any node coordinates; requests fan out to shard copies

Smart clients avoid an extra network hop and remove a central bottleneck.

3. Spreading Reads Across Replicas

  • Cassandra drivers use load-balancing policies such as token-aware plus data-centre-aware round robin, and dynamic snitch logic on servers routes reads away from slow replicas.

  • MongoDB read preferences (primary, primaryPreferred, secondary, nearest) spread reads, at the cost of possibly stale data from secondaries.

  • Elasticsearch spreads search requests across primary and replica shards, using adaptive replica selection.

4. Rebalancing and Scaling

  • Add nodes and let the system move token ranges, slots or chunks.

  • Rebalancing consumes I/O and network; schedule large moves off-peak or throttle them.

5. Handling Hot Spots

Even data distribution does not guarantee even traffic:

  • Hot partitions (a viral post) need key redesign (salting, bucketing), caching or read replicas.

  • Hot shards caused by monotonic shard keys need hashed keys.

  • Request throttling per tenant protects shared clusters.

6. Connection Management

  • Connection pooling in drivers.

  • Limit concurrent requests per node to avoid overload.

  • Use proxies (such as Envoy or vendor-specific proxies) where clients cannot be cluster-aware.

Example

A Cassandra cluster of 12 nodes across two data centres:

  • The application uses a driver with token-aware, DC-aware load balancing and LOCAL_QUORUM.

  • Requests go straight to local replicas owning each partition.

  • The dynamic snitch avoids a node with high latency during compaction.

  • Adding three nodes redistributes token ranges, and streaming moves data in the background.

Pitfalls

  • Placing a generic TCP load balancer in front of a database that needs key-aware routing, adding hops and hiding topology.

  • Reading from secondaries without accepting staleness.

  • Ignoring skewed traffic; monitor per-partition and per-node metrics.

Interview Tip

Separate data distribution from request routing and replica selection, give examples of token-aware drivers and MongoDB routers, and mention hot partitions as the case where balanced data still creates unbalanced load.

29

What role does caching play in NoSQL database performance?

Caching improves NoSQL performance by serving frequently read data from memory instead of disk or remote replicas, reducing latency, database load and cost. It happens at several layers: inside the database (block caches, row caches, memory-resident working sets), in dedicated caches in front of the database (Redis, Memcached, DynamoDB Accelerator), and in the application or client. Caching must be paired with invalidation, TTLs and stampede protection, or it serves stale or inconsistent data.

Read full answer

Applies toNoSQL performance tuning (MongoDB WiredTiger cache, Cassandra key/row caches, HBase BlockCache, DynamoDB DAX, Redis/Memcached as external caches)

Built-In Database Caching

Database Cache mechanism
MongoDB (WiredTiger) Internal cache (by default roughly half of RAM minus 1 GB) plus the OS file cache; performance is best when the working set and indexes fit in memory
Cassandra OS page cache, key cache (partition index positions), optional row cache, bloom filters in memory
HBase BlockCache for reads, MemStore for writes
Couchbase Memory-first design with a managed cache per bucket
Redis Data itself lives in memory

External Cache Patterns

Cache-aside (lazy loading)

  1. Read from the cache.

  2. On a miss, read from the database and store in the cache with a TTL.

  3. On writes, update the database and invalidate or update the cache entry.

def get_product(pid):
    data = cache.get(f"product:{pid}")
    if data is None:
        data = db.products.find_one({"_id": pid})
        cache.set(f"product:{pid}", data, ex=300)
    return data

Write-through: writes go to cache and database together, keeping the cache fresh at the cost of write latency.

Write-back (write-behind): writes go to the cache and are flushed later; fast, but risks data loss if the cache fails.

Read-through managed caches: DynamoDB Accelerator (DAX) sits in front of DynamoDB and reduces read latency from single-digit milliseconds to microseconds for cached items.

Benefits

  • Lower latency for hot data (memory reads are orders of magnitude faster than disk or network round trips to other replicas).

  • Reduced database read capacity, which lowers cost for managed services that charge per read.

  • Absorbs hot keys and traffic spikes.

Risks and Mitigations

Risk Mitigation
Stale data TTLs, invalidation on writes, event-driven invalidation (change streams, CDC)
Cache stampede (many misses at once) Request coalescing, locks per key, early refresh, jittered TTLs
Cold start after restart Warm-up jobs, persistent caches
Inconsistency between cache and DB Delete-on-write rather than update-on-write; short TTLs for volatile data
Memory pressure Eviction policies (LRU, LFU), size limits, caching only hot data
Cache as single point of failure Replicated cache clusters; application falls back to the database

What to Cache

  • Read-heavy, rarely changing data: product details, configuration, user profiles.

  • Expensive query results and aggregates.

  • Not usually: rapidly changing balances or inventory counts that require strong consistency.

Example

A news site stores articles in MongoDB. Article pages are read about 1,000 times for every update. A Redis cache-aside layer with a 5-minute TTL and invalidation on publish serves most reads from memory, cutting database read load sharply and keeping p95 page data latency in single-digit milliseconds.

Interview Tip

Cover built-in and external caching, explain cache-aside vs write-through vs write-back, and always discuss invalidation, TTLs and stampede protection. Interviewers often catch candidates who add a cache without saying how it stays fresh.

30

How do NoSQL databases ensure high availability?

NoSQL databases ensure high availability by replicating data across multiple nodes, racks, availability zones and regions, detecting failures automatically and failing over (leader election) or routing around failed replicas (leaderless designs), supporting tunable consistency so operations can succeed with some replicas down, and repairing replicas after failures. Managed services add multi-zone replication and global tables by default.

Read full answer

Applies toMongoDB replica sets, Cassandra/ScyllaDB, DynamoDB, Cosmos DB, Couchbase, Redis Sentinel/Cluster

Core Mechanisms

1. Replication

  • Each piece of data is stored on several nodes (commonly 3).

  • Replicas are placed across failure domains (racks, zones, regions).

2. Failure detection

  • Heartbeats and gossip protocols detect unresponsive nodes (Cassandra gossip, MongoDB heartbeats every 2 seconds, Redis Sentinel monitoring).

3. Failover or routing around failures

Design Behaviour on node failure
Single-leader (MongoDB, Redis) Remaining members elect a new primary, typically within seconds; clients retry writes
Leaderless (Cassandra, ScyllaDB) No failover: other replicas keep serving requests if the consistency level can still be met
Managed (DynamoDB, Cosmos DB) Provider handles replica replacement transparently across zones

4. Tunable consistency

  • With replication factor 3, LOCAL_QUORUM tolerates one replica down; ONE tolerates two (with weaker consistency).

5. Hinted handoff and repair

  • Writes for unavailable replicas are stored as hints and replayed.

  • Read repair and anti-entropy repair resynchronize replicas.

6. Multi-region deployment

  • Cassandra multi-data-centre replication, MongoDB replica set members in several regions, DynamoDB global tables, Cosmos DB multi-region writes.

  • Protects against regional outages; trade-off is cross-region latency or eventual consistency.

Availability Math (Rough)

  • Single node at 99.9% availability: about 8.8 hours of downtime a year.

  • With three independent replicas and an operation needing only one, the chance all three are down at once is very small. Real failures are often correlated (same zone, same bug, same bad deployment), which is why replicas are spread across failure domains and upgrades are rolled out gradually.

Operational Practices

  • Rolling upgrades one node at a time.

  • Backups and point-in-time recovery: replication copies mistakes (accidental deletes), so backups are separate protection.

  • Monitoring: replication lag, node health, disk space, repair status.

  • Capacity headroom: when one node fails, others absorb its load.

  • Client configuration: retryable writes (MongoDB), driver retry policies, timeouts, multiple contact points.

  • Chaos testing and failover drills.

Example

A MongoDB replica set has members in three availability zones with w: "majority". If the primary’s zone fails, the two remaining members elect a new primary within about 10–12 seconds by default; the driver retries writes automatically, and no majority-acknowledged writes are lost.

A Cassandra cluster with replication factor 3 per data centre and LOCAL_QUORUM keeps serving reads and writes during one node failure with no election at all.

Trade-offs

  • More replicas increase cost and write amplification.

  • Synchronous or majority writes add latency.

  • Highly available AP configurations may serve stale data or require conflict resolution.

  • Multi-region setups add complexity in consistency and operations.

Interview Tip

Explain replication across failure domains, failover in leader-based systems vs routing around failures in leaderless ones, and tunable consistency. Mentioning that backups are still required because replication copies mistakes is a detail interviewers value.

31

How do NoSQL databases handle complex queries such as joins?

Most NoSQL databases avoid joins at query time and handle relationships through data modelling: embedding related data, denormalizing and duplicating fields, and creating one table or index per query pattern. When joins are needed, options include limited built-in joins (MongoDB $lookup, Couchbase SQL++ joins), application-side joins, precomputed views and aggregates, and moving complex analytics to search engines, data warehouses or processing frameworks such as Spark.

Read full answer

Applies todocument, wide-column and key-value stores (MongoDB, Couchbase, Cassandra, DynamoDB); graph databases handle relationships differently, through traversals

1. Model Data to Avoid Joins

Embedding (document stores)

{"_id": "ord-501", "customer": {"id": 42, "name": "Asha"},
 "items": [{"sku": "SHOE-7", "name": "Trail Runner", "qty": 1, "price": 89}]}

One read returns the order with customer and product names.

Query-first tables (wide-column)

In Cassandra, create orders_by_customer and orders_by_product tables, writing each order to both. Each query reads one partition; writes do more work.

Single-table design (DynamoDB)

Store related entities under the same partition key with different sort keys:

PK = CUSTOMER#42  SK = PROFILE          → customer data
PK = CUSTOMER#42  SK = ORDER#2026-05-01 → order summary

A single Query on PK = CUSTOMER#42 returns the customer and recent orders together.

2. Built-In Join Support

MongoDB $lookup

db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $lookup: { from: "customers", localField: "customerId",
               foreignField: "_id", as: "customer" } },
  { $unwind: "$customer" },
  { $project: { total: 1, "customer.name": 1 } }
])

Works well on small, indexed sets; on large sharded collections it can be expensive.

Couchbase SQL++ supports JOIN, NEST and UNNEST with indexes.

3. Application-Side Joins

  • Fetch orders, collect customer IDs, then fetch customers in a batch ($in query or BatchGetItem).

  • Fine for small result sets; the application handles the merging.

4. Precomputation

  • Materialized views or aggregate collections updated on write or by streams (change streams, DynamoDB Streams, CDC).

  • Counters and summaries maintained at write time (commentCount on a post).

5. Offload Complex Queries

Need Tool
Full-text search and faceted filtering Elasticsearch / OpenSearch fed from the database
Ad-hoc analytics and reporting with joins Data warehouse (BigQuery, Snowflake, Redshift) via ETL/ELT
Large-scale batch joins Spark, Presto/Trino on exported data
Relationship traversals Graph database

Trade-offs

Approach Benefit Cost
Embedding / denormalization Fast single reads Duplicated data, update complexity
Query-specific tables Predictable performance More writes, storage, sync logic
$lookup / built-in joins Flexibility Slower at scale, especially across shards
Application joins Simple to implement More round trips, code complexity
Offloading to analytics Rich queries Data latency, extra infrastructure

Interview Tip

Explain that NoSQL handles joins mainly through modelling (embedding, denormalization, query-first tables), then mention $lookup, application joins and offloading to warehouses or search engines. Saying that frequent complex joins may indicate a relational database is the better fit shows sound judgement.

32

What is MapReduce, and how is it used in NoSQL databases?

MapReduce is a programming model for processing large datasets in parallel: a map function transforms each input record into key-value pairs, the framework groups (shuffles) values by key, and a reduce function combines each group into a result. It was popularized by Google and Hadoop. In NoSQL databases it was used for batch aggregations across many nodes, but most systems now favour aggregation pipelines, SQL-like engines and Apache Spark because they are faster and easier to use.

Read full answer

Applies toHadoop MapReduce, HBase with MapReduce jobs, historical MongoDB and CouchDB map/reduce features, Riak MapReduce; modern alternatives such as MongoDB aggregation pipelines and Apache Spark

How It Works

  1. Split: input data is divided into chunks processed on different nodes.

  2. Map: each chunk’s records produce (key, value) pairs.

  3. Shuffle and sort: pairs with the same key are sent to the same reducer.

  4. Reduce: each reducer aggregates the values for its keys.

  5. Output: results are written to storage.

Example: Revenue per City

Input documents:

{"city": "Pune", "total": 120}
{"city": "Delhi", "total": 80}
{"city": "Pune", "total": 50}
  • Map: emit ("Pune", 120), ("Delhi", 80), ("Pune", 50).

  • Shuffle: "Pune" → [120, 50], "Delhi" → [80].

  • Reduce: "Pune" → 170, "Delhi" → 80.

A short, runnable Python illustration of the same logic:

from collections import defaultdict

orders = [{"city": "Pune", "total": 120}, {"city": "Delhi", "total": 80},
          {"city": "Pune", "total": 50}]

mapped = [(o["city"], o["total"]) for o in orders]          # map
groups = defaultdict(list)
for city, total in mapped:                                    # shuffle
    groups[city].append(total)
result = {city: sum(vals) for city, vals in groups.items()}  # reduce
print(result)  # {'Pune': 170, 'Delhi': 80}

Use in NoSQL Systems

System MapReduce usage
HBase Hadoop MapReduce jobs read and write HBase tables for batch processing
MongoDB mapReduce command with JavaScript functions; deprecated since MongoDB 5.0 in favour of the aggregation pipeline
CouchDB Views are defined by map and reduce functions and are incrementally maintained indexes, still a core feature
Riak Supported MapReduce queries over buckets (Riak KV)
Cassandra Integrated with Hadoop historically; today Spark with the Spark Cassandra Connector is typical

Modern Alternative: MongoDB Aggregation Pipeline

db.orders.aggregate([
  { $group: { _id: "$city", revenue: { $sum: "$total" } } }
])

It runs natively (no JavaScript), uses indexes for $match stages, and is usually much faster.

Why MapReduce Declined

  • Disk-heavy: Hadoop MapReduce writes intermediate results to disk between stages, making multi-step jobs slow.

  • Verbose to write.

  • Batch only: high latency, unsuitable for interactive queries.

  • Spark keeps data in memory across stages and offers SQL, DataFrames and streaming; SQL engines such as Presto/Trino and Hive offer declarative queries.

Where the Idea Still Matters

  • The map, shuffle, reduce pattern underlies Spark, Flink and many distributed aggregation systems.

  • Understanding shuffles helps diagnose performance problems such as data skew (one key with most records overloading one reducer).

Interview Tip

Explain map, shuffle and reduce with a small example, mention how NoSQL systems used it, and say that MongoDB deprecated mapReduce in favour of the aggregation pipeline and that Spark replaced Hadoop MapReduce for most workloads. Mentioning data skew shows practical understanding.

33

Do NoSQL databases support transactions, and how are they implemented?

Yes. The claim that “NoSQL has no transactions” is outdated. Almost all NoSQL databases guarantee atomic single-item or single-document operations, many offer conditional writes (compare-and-set), and several support multi-item ACID transactions: MongoDB multi-document transactions, DynamoDB TransactWriteItems, Cosmos DB transactional batches, and others. They are implemented with techniques such as write-ahead logs, snapshot isolation (MVCC), two-phase commit across shards, and consensus protocols, usually with limits on scope, size and cost.

Read full answer

Applies toMongoDB, DynamoDB, Cassandra/ScyllaDB, Cosmos DB, Couchbase, Redis, FoundationDB

Levels of Transaction Support

Level Description Examples
Single-item atomicity One document or item updated atomically, including nested fields All major NoSQL stores
Conditional writes / CAS Write only if a condition holds (version, existence) DynamoDB condition expressions, Cassandra lightweight transactions (IF), MongoDB findOneAndUpdate with filters
Partition-scoped transactions Atomic batch within one partition Cosmos DB transactional batch, Cassandra batches in one partition
Multi-item ACID Several items or documents, possibly across partitions or shards MongoDB multi-document transactions, DynamoDB transactions, Couchbase distributed ACID transactions, FoundationDB

Examples

MongoDB multi-document transaction

const session = client.startSession();
session.withTransaction(async () => {
  await accounts.updateOne({ _id: "A", balance: { $gte: 500 } },
                           { $inc: { balance: -500 } }, { session });
  await accounts.updateOne({ _id: "B" }, { $inc: { balance: 500 } }, { session });
}, { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } });

DynamoDB transaction

{"TransactItems": [
  {"Update": {"TableName": "Accounts", "Key": {"id": {"S": "A"}},
    "UpdateExpression": "SET balance = balance - :amt",
    "ConditionExpression": "balance >= :amt",
    "ExpressionAttributeValues": {":amt": {"N": "500"}}}},
  {"Update": {"TableName": "Accounts", "Key": {"id": {"S": "B"}},
    "UpdateExpression": "SET balance = balance + :amt",
    "ExpressionAttributeValues": {":amt": {"N": "500"}}}}
]}

Cassandra lightweight transaction

INSERT INTO usernames (name, user_id) VALUES ('asha', 'u42') IF NOT EXISTS;

How They Are Implemented

  • Single-document atomicity: the storage engine applies the whole update under a lock or as one log entry.

  • MongoDB: WiredTiger uses MVCC snapshots for isolation; replica sets commit through the oplog with majority write concern; sharded transactions use a two-phase commit coordinated by a shard.

  • DynamoDB: a transaction coordinator applies a two-phase protocol across items, with conflict detection and idempotency tokens (ClientRequestToken).

  • Cassandra LWT: a Paxos round among replicas to agree on the conditional update; general-purpose ACID transactions based on the Accord protocol (CEP-15) are planned for a release after Cassandra 5.0.

  • FoundationDB: optimistic concurrency with a central ordering of commits, giving serializable transactions.

Limits and Costs

System Typical constraints
MongoDB Transactions should be short (default 60-second lifetime limit); performance cost, especially across shards
DynamoDB Up to 100 items per transaction; transactional writes consume about twice the capacity of standard writes
Cosmos DB Transactional batch within a single logical partition
Cassandra LWT requires multiple round trips; avoid on hot paths

Design Advice

  • Prefer modelling so that a business operation touches one document or partition; use multi-item transactions only where needed.

  • Keep transactions short and retry on transient conflicts.

  • Use idempotency keys for retries.

  • For cross-service workflows, use sagas rather than distributed database transactions.

Interview Tip

State clearly that modern NoSQL databases support transactions, explain the levels (single-item, conditional, multi-item), give one example, and mention scope limits and costs. Correcting the “no transactions” myth with specifics is what interviewers want to hear.

34

How do indexing strategies differ between NoSQL and relational databases?

Both families use similar structures (mostly B-trees, plus hash, inverted and spatial indexes), but they differ in what gets indexed and how distribution affects indexes. Relational databases index columns of normalized tables to support flexible, ad-hoc queries and joins, with indexes stored alongside data on one server. NoSQL databases often design around a primary key or partition key, index nested fields and arrays, and must deal with secondary indexes spread across shards, which makes queries not using the partition key more expensive. Many NoSQL designs replace indexes with denormalized query tables.

Read full answer

Applies toPostgreSQL, MySQL, SQL Server compared with MongoDB, Cassandra, DynamoDB, Couchbase, Elasticsearch

Comparison

Aspect Relational NoSQL
Primary access Primary key index (often clustered) Partition key + sort/clustering key defines data placement and order
Secondary indexes Common and flexible; any column combination Available but constrained: per-shard local indexes or eventually consistent global indexes
Nested data JSON columns can be indexed (PostgreSQL GIN, expression indexes) Native indexing of nested fields and arrays (MongoDB multikey)
Query planner Mature cost-based optimizer with statistics Simpler planners; queries expected to match designed patterns
Join support Indexes support joins Joins rare; denormalized tables replace many indexes
Distribution Usually single node (or partitioned tables) Indexes partitioned across nodes
Consistency of index Updated in the same transaction Local indexes are consistent with data; global indexes may lag
Full-text Built-in options (PostgreSQL tsvector) Dedicated search engines with inverted indexes

NoSQL Index Approaches

DynamoDB

  • Primary key: partition key (+ optional sort key).

  • Local Secondary Index (LSI): same partition key, different sort key; must be defined at table creation; strongly consistent reads possible.

  • Global Secondary Index (GSI): different partition and sort keys; a separate, eventually consistent copy of projected attributes with its own capacity.

MongoDB

  • B-tree indexes on any field, nested field or array (multikey), compound, text, geospatial, wildcard, TTL.

  • In sharded clusters each shard has local indexes; queries without the shard key are broadcast to all shards.

Cassandra

  • Primary key determines partitioning and order.

  • Secondary indexes exist (including Storage-Attached Indexes, SAI, in Cassandra 5.0), but the traditional approach is one table per query.

Search engines

  • Inverted indexes map terms to documents for full-text queries; often used beside NoSQL or relational stores.

Local vs Global Secondary Indexes

Type Stored Query cost Write cost
Local (per shard) With data on each shard Query without partition key hits all shards Updated locally, consistent
Global Partitioned by the index key across the cluster Targeted lookup by index key Extra distributed write; often asynchronous

Example

Requirement: “find orders by customer and by status”.

  • Relational: CREATE INDEX ON orders (customer_id, created_at) and CREATE INDEX ON orders (status); the planner picks one.

  • DynamoDB: table keyed by customerId + createdAt; add a GSI keyed by status + createdAt (watch for hot partitions if few statuses exist; add a sharded suffix).

  • Cassandra: tables orders_by_customer and orders_by_status_day, written together.

Trade-offs

  • Every index slows writes and uses storage in both worlds.

  • Global indexes in distributed systems add replication lag and cost.

  • NoSQL designs push indexing decisions earlier, into the data model.

Interview Tip

Explain that underlying structures are similar but distribution changes everything: partition keys, local vs global secondary indexes, and query-first tables. Mentioning DynamoDB LSI vs GSI and the eventual consistency of GSIs is a strong, concrete detail.

35

How do storage formats like JSON, BSON and binary affect NoSQL performance?

Storage formats affect parse speed, storage size, query efficiency and flexibility. JSON is human-readable and universal but text-based, so it is slower to parse and larger. BSON (Binary JSON, used by MongoDB) adds types and length prefixes so fields can be traversed and skipped quickly, at the cost of sometimes being larger than JSON. Compact binary formats (Protocol Buffers, Avro, MessagePack, columnar files) are fastest and smallest but require schemas or tooling. Databases also use internal binary formats and compression that matter more than the wire format.

Read full answer

Applies toMongoDB (BSON), Couchbase (JSON), PostgreSQL JSONB (for comparison), Cassandra and HBase internal formats, Avro/Protobuf/MessagePack, Parquet/ORC for analytics

Comparison

Format Type Strengths Weaknesses Typical use
JSON (text) Self-describing text Readable, universal, easy debugging Larger, slower to parse, limited types (no dates, binary, 64-bit integers in JavaScript) APIs, Couchbase documents, logs
BSON Self-describing binary Rich types (dates, ObjectId, Decimal128, binary), fast field traversal via length prefixes Field names repeated per document; sometimes larger than JSON MongoDB storage and wire protocol
MessagePack / CBOR Self-describing binary Compact, fast, JSON-like Less tooling for queries Caches, IoT (CBOR), RPC
Protocol Buffers Schema-based binary Very compact, fast, strong schema evolution Requires schema and generated code; not self-describing gRPC, events, storing values in key-value stores
Avro Schema-based binary Compact, schema evolution with registry Needs schema at read time Kafka events, data pipelines
Parquet / ORC Columnar binary Excellent compression and scan speed for analytics Not for row-by-row updates Data lakes, analytics

Performance Effects

Parsing and traversal

  • Text JSON must be scanned character by character.

  • BSON stores the length of each element, so the engine can skip fields without parsing them, and values have explicit types.

Size

  • Self-describing formats repeat field names in every document. In a collection with millions of documents, long names such as customerShippingAddressLine1 add significant storage and memory use. Short, clear names help.

  • Schema-based formats store only values, making them much smaller.

Compression

  • MongoDB’s WiredTiger compresses data on disk (snappy by default; zlib and zstd available) and indexes with prefix compression; Cassandra compresses SSTables (LZ4 by default).

  • Compression often reduces size more than the choice of encoding, trading CPU for I/O.

Query capability

  • Formats the database understands (BSON, JSON in Couchbase, PostgreSQL JSONB) allow indexing and querying nested fields.

  • Opaque binary values (a Protobuf blob in Redis or DynamoDB) cannot be queried by the database; only the key is usable.

Type fidelity

  • BSON’s Decimal128 avoids floating-point errors for money; Date and ObjectId types are native.

  • JSON numbers can lose precision for large integers in some languages.

Choosing

  • Need ad-hoc queries on fields: a format the database indexes natively (BSON, JSON documents, JSONB).

  • Values only fetched by key, high throughput: compact binary (Protobuf, MessagePack) stored as values.

  • Event streams: Avro or Protobuf with a schema registry.

  • Analytics: columnar formats such as Parquet.

  • Interoperability and debugging: JSON at the API layer.

Interview Tip

Contrast text JSON, BSON and schema-based binary formats on parse speed, size and queryability, and mention compression and repeated field names as practical performance factors. Pointing out that opaque binary values cannot be queried by the database is a common follow-up.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 35 NoSQL answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All System Design subjects