NoSQL Databases: Document, Key-Value, Column-Family, Graph

Explore NoSQL database types, CAP theorem implications, and when to choose MongoDB, Cassandra, DynamoDB, or graph databases over relational systems.

published: reading time: 34 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

NoSQL databases organize data as documents, key-value pairs, column families, or graphs, with each model favoring different access patterns and query trade-offs. This guide covers shard-key design, replication and consistency choices, failure modes, and operational concerns across MongoDB, Cassandra, DynamoDB, Redis, and graph stores. Use the comparisons to decide whether a NoSQL system solves a concrete workload need or whether a relational database is the simpler fit.

NoSQL Databases: Document, Key-Value, Column-Family, and Graph Databases

Introduction

NoSQL is a broad label for several data models, not one shared consistency or scaling strategy. A key-value cache, a document store, a wide-column database, and a graph database answer different kinds of queries.

Choose from the workload: the reads and writes the application needs, the shape of each query, the consistency guarantees it depends on, how data will be partitioned, and what the team can operate. The same e-commerce catalog can be represented in all four models, but each design makes different queries easy.

A decision matrix: one e-commerce catalog, four models

Model Example catalog query Decisions to make Operational fit
Key-value Fetch the full product record by product:SKU-42. Exact-key reads and writes are straightforward. Category filters need another index or an application-side lookup. In a clustered store, check how keys map to partitions. Useful for cache entries or records accessed by a known key. Decide what happens on expiration, eviction, or cache loss before treating it as the source of truth.
Document Fetch a product document with its variants, or filter products by an indexed category. Choose which fields to embed, which to reference, and which filters need indexes. In MongoDB, a single-document write is atomic; multi-document transactions and read guarantees depend on the product and configuration. Fits records that are commonly read together. Check index size, document growth, and how schema changes will be deployed.
Wide-column Read a category’s products ordered by price from a table partitioned by category and bucket. In Cassandra, the partition key selects a token range and clustering columns order rows within a partition. Bound partition growth and avoid concentrating traffic on one key. Fits known query patterns that can be served from a small number of partitions. Team members need to understand partition sizing, replication, and repair.
Graph Traverse product-to-category, product-to-brand, and related-product edges for recommendations. Model the relationships the traversal follows. Query cost and distribution depend on the graph engine and the shape and depth of the traversal. Fits relationship-heavy queries. Check the graph product’s transaction, replication, partitioning, and operations model rather than assuming all graph stores behave alike.

Before choosing, write down expected reads and writes, query shapes, consistency needs, data growth, recovery targets, and who will run the system. Then benchmark representative queries with realistic data. A model name alone does not predict latency.

Topic-Specific Deep Dives

Sharding Fundamentals

Sharding distributes data across multiple nodes. It can increase storage and throughput, but it also adds routing, rebalancing, and failure handling. Queries that touch many partitions may cost more than single-partition lookups, so model the expected query shape before selecting a shard key.

Hash-based sharding can spread keys across nodes, but a range query may need to visit many partitions. Range-based layouts can keep nearby values together, but skewed keys can create hot spots. Consistent hashing is one way to limit remapping when nodes change; products differ in how they assign ranges and rebalance data. Changing a partition key later can require a data migration.

The examples below separate hash-based distribution, range-oriented queries, and application-managed routing. They are patterns, not interchangeable vendor implementations.

Sharding Patterns Deep Dive

The same shard key can behave differently across products. These common patterns show what to check.

Hash-Based Sharding

One simple application-level scheme is shard = hash(key) % shard_count. It is easy to understand, but changing the shard count remaps many keys. Range queries also tend to visit multiple shards. Hashing helps distribute keys; it cannot guarantee an even workload when a few keys receive most of the traffic. This formula is illustrative: production routing needs a stable hash and a migration plan when the shard map changes.

# Application-level hash sharding
def get_shard(key, num_shards=16):
    return abs(hash(key)) % num_shards

shards = [connect(f"shard_{i}.db") for i in range(num_shards)]
key = "user:12345"
shard = shards[get_shard(key)]

MongoDB supports both hashed and ranged shard keys; its balancer moves chunks between shards. Cassandra maps hashed partition keys to token ranges assigned to nodes, while clustering columns order rows within a partition. These are different designs. Check the product documentation and selected configuration before applying one system’s routing assumptions to another.

Consistent Hashing

The idea is to minimize shuffling when nodes join or leave. Instead of modulo on the hash, data goes to the first node clockwise on the ring.

graph LR
    subgraph "Hash Ring"
        H1["hash(A)"];
        H2["hash(B)"];
        H3["hash(C)"];
        H4["hash(D)"];
    end
    A["Node A<br/>Range: H1→H2"] --> B["Node B<br/>Range: H2→H3"];
    B --> C["Node C<br/>Range: H3→H4"];
    C --> D["Node D<br/>Range: H4→H1"];
    D --> A;

With a ring-based design, changing membership can move ranges between nodes rather than remapping every key. The amount of movement and the recovery procedure depend on the implementation and its replication settings.

Advanced Sharding Strategies

Range-Based Sharding

Cassandra does not use range-based partitioning: it hashes the partition key and uses clustering columns to order rows within that partition. Other systems can partition by key ranges, which may help range queries but can create hotspots when values are skewed.

Cassandra hashes the partition key to place data; clustering columns provide order within a partition. A time-series table can include a time bucket in its partition key and use the timestamp as a clustering column, keeping each partition bounded while supporting time-window reads:

-- Cassandra: time-bucketed partition with ordered rows
CREATE TABLE sensor_readings (
    device_id uuid,
    month text,  -- '2026-03'
    reading_time timestamp,
    temperature float,
    PRIMARY KEY ((device_id, month), reading_time)
);

Application-Level Sharding

Some systems expose routing details to clients. Memcached clients commonly hash keys to servers. Redis Cluster clients follow the cluster’s slot map and handle redirection responses when ownership changes. These approaches are not the same as an application inventing its own shard map.

# Application-level sharding with Redis Cluster-like routing
class ShardedRedis:
    def __init__(self, nodes):
        self.nodes = nodes
        self.slot_map = self._build_slot_map(16384, nodes)

    def _slot_for_key(self, key):
        return crc16(key) % 16384

    def get(self, key):
        slot = self._slot_for_key(key)
        node = self._node_for_slot(slot)
        return node.get(key)

Sharding Anti-Patterns

Hot partition keys: In a partitioned store, a low-cardinality key such as status or region can concentrate traffic on a small number of partitions. A single popular entity can do the same even when the rest of the key space is well distributed.

Unbounded partitions: A time-series or conversation partition can keep growing if its key has no bucket or retention boundary. In Cassandra, plan a bucket size that fits the read pattern and expected data volume; validate it against the deployed version and workload.

Cross-partition transactions: An operation that spans partitions may need coordination, depending on the database and transaction scope. That can add latency and failure cases. Keep related writes together when the data model permits, and check what the product guarantees across partitions.

Trade-off Analysis

When Relational Still Wins

Consider an order that reserves stock, records a payment attempt, and creates an order row. A relational database can enforce unique keys and foreign keys and commit related updates in one transaction. That is a good fit when correctness depends on those invariants holding together.

Some nonrelational products also support transactions, conditional writes, or uniqueness constraints. Their scope, isolation, limits, and behavior across partitions differ by product and configuration. Compare the guarantees the application needs with the actual feature set; do not assume the word “NoSQL” means transactions are unavailable.

Relational systems are also a natural fit when the application needs joins or queries that change as the product evolves. Start there when the data and workload fit, then measure. Move to a different model when a specific query, scale limit, or distribution requirement justifies the added modeling and operational work.

When to Use / When Not to Use

When to Consider a Nonrelational Model:

  • The document, key-value, wide-column, or graph model matches the queries the application actually runs.
  • A measured workload needs partitioning or distribution that is difficult to achieve with the current relational design.
  • The team can state how the store handles consistency, transactions, failover, backups, and recovery for the required operations.

When a Relational Model May Be Safer:

  • A business invariant spans related rows, such as one payment per order or inventory that must not go below zero.
  • Queries depend on joins, foreign keys, uniqueness constraints, or ad-hoc reporting.
  • The team cannot yet operate the candidate database or has not established how it will restore data after failure.

Production Failure Scenarios

These examples show how a workload can expose a database limit. Symptoms and recovery time depend on the product, configuration, and traffic pattern.

DynamoDB Thundering Herd

DynamoDB can adapt to uneven traffic, but a hot key can still be throttled if demand exceeds the capacity available to serve it. The result depends on item size, table capacity mode, partition-key distribution, and the request mix. Retries without backoff can amplify the spike.

Cache unusually popular items, use exponential backoff with jitter for retryable errors, and inspect throttling and consumed-capacity metrics by operation. For a read-heavy item that cannot be served from cache, a write-sharded representation can spread reads across keys, but it adds fan-out and makes updates more involved. Choose that trade-off from measured traffic, and do not assume adaptive capacity or partition changes provide a fixed recovery time.

Cassandra Compaction Storms

Cassandra compacts SSTables periodically to remove tombstones and overwrite dead data. Under heavy write workloads, compactions can fall behind. When compaction finally runs, it reads and rewrites large amounts of data, consuming disk I/O and CPU. This creates a feedback loop: writes accumulate faster, compaction falls further behind, and read performance degrades because the database is scanning past dead data.

Compaction pressure rises when SSTables are created faster than the cluster can compact them. The symptoms depend on the table’s compaction strategy, disk capacity and I/O, write rate, and tombstone distribution; no single queue length or headroom percentage fits every cluster.

Watch pending compactions, disk use, read latency, and write throughput together. Choose a compaction strategy for the table’s data lifecycle and query pattern, then validate it against production-like workloads. If compaction falls behind, reduce or shape writes where possible and check disk and CPU saturation before adding nodes. Node expansion also takes time and consumes resources while data is rebalanced.

MongoDB Shard Imbalance After Chunk Migration

MongoDB’s balancer redistributes chunks when the sharded collection meets the configured balancing policy. Migrations use network, disk, and CPU, so their effect on application latency depends on document and chunk sizes, cluster headroom, network throughput, and concurrent workload. There is no useful fixed duration or transfer rate for a migration.

Review balancer activity, per-shard load, and query latency together. A skewed chunk count alone does not prove that the application is imbalanced: a shard key can distribute chunks evenly while a few values receive most of the traffic. If migrations compete with foreground work, schedule balancing in an appropriate window or pause it while investigating; use the controls and operational procedure documented for your MongoDB server version. Check shard-key indexes and the distribution of actual requests before forcing data movement.

Redis Dataset Eviction Under Memory Pressure

Redis eviction behavior depends on the configured maxmemory policy. If Redis is a cache, applications should expect misses and protect the backing store from a sudden burst of fallback reads. If it holds primary data, eviction may be unacceptable; choose a policy and persistence setup that match the data’s role.

Set memory limits with the process, allocator, persistence, replication, and host memory needs in mind. Redis LRU and LFU policies use approximations rather than inspecting every key on each eviction. Watch used_memory, host memory, evicted_keys, and latency; interpret fragmentation metrics in context instead of relying on one universal threshold. Test the selected policy with a representative key distribution and failure behavior.

Network Partitions and Replica Divergence

During a Cassandra network partition, whether a read or write can succeed depends on replica placement, datacenter topology, and the operation’s consistency level. A low consistency level may allow acknowledgments from different replica sets at different times; quorum is not a universal fix if the chosen level does not match the replication strategy and failure model.

Define the required guarantees for each operation, test the relevant partition scenarios, and use the consistency-level and repair guidance for the deployed Cassandra version. Repairs reconcile replica data, but they do not decide business-level conflicts such as two valid updates to the same inventory record.

Common Pitfalls / Anti-Patterns

  1. Choosing a model before listing its queries: For Cassandra and DynamoDB, map each important query to a partition key, sort or clustering key, and index before building the schema. Other models also need representative query shapes, even when they allow more flexible access.

  2. Ignoring consistency requirements: With asynchronous replication or a read mode that permits older data, a read may not reflect a recent write. Check the read and write guarantees for each operation in the selected product and configuration.

  3. Unbounded partition growth: In Cassandra, a partition can grow without bound if its key does not include a bucket or retention boundary. For time-series data, consider a partition key such as (device_id, month) and a timestamp clustering column; choose the bucket from expected row volume and query windows.

  4. Over-reliance on secondary indexes: Index behavior, consistency, cost, and query limits vary by product. Check the query plan and benchmark the exact index and workload before depending on it.

  5. Treating access-pattern modeling as unique to NoSQL: Every database schema affects query cost. Cassandra and DynamoDB often need tables shaped around known queries, while document and graph stores organize data differently. Model both the domain and the queries the application must serve.

  6. Skipping backup and recovery testing: Many NoSQL systems have complex backup mechanisms. Test recovery procedures regularly or you will lose data eventually.

  7. Underestimating operational complexity: Each NoSQL system has its own operational quirks. Make sure your team has training and runbooks for your specific system.

  8. Letting partitions grow without a plan: In Cassandra, very large partitions can increase storage, compaction, and read costs. Estimate row growth for the chosen partition key and validate the design against the workload.

  9. Assuming linear scalability: Adding nodes does not instantly double your capacity. Rebalancing takes time and causes temporary load spikes you did not plan for.

Workload Examples

A Cassandra table for conversation history might use (conversation_id, time_bucket) as its partition key and a timestamp as a clustering column. That supports ordered reads within a bounded bucket. An application asking for a conversation across many buckets must query and combine those partitions. Measure bucket size and request patterns instead of assuming that adding nodes makes every query faster.

A DynamoDB table can serve known access patterns through its partition key, optional sort key, and secondary indexes. A query not supported by those keys or indexes may require a scan or another data representation. Adaptive capacity can help uneven access patterns within documented limits; it does not make capacity unlimited or remove the need to design for hot keys. Check current service limits and test the chosen capacity mode with representative item sizes.

Replication Topologies

How you replicate across regions determines what happens when partitions occur, how consistent your data is, and how much latency your writes tolerate.

Multi-Region Replication Topologies

Single-Leader Replication

One region is primary. Writes go there, then replicate to secondaries; depending on the read preference, clients may read from a replica that has not applied the latest write.

graph LR
    Primary["Primary Region<br/>US-East"] --> Replica1["Replica<br/>US-West"];
    Primary --> Replica2["Replica<br/>EU-West"];
    Client1["Client<br/>US-East"] --> Primary;
    Client2["Client<br/>US-West"] --> Replica1;

In a single-leader setup, writes go to the primary and replicas may lag. Remote writes pay the cost of reaching that primary, and failover behavior depends on the database and its configuration. MongoDB replica sets and PostgreSQL streaming replication are examples of primary-replica designs; deployments can automate failover.

Multi-Leader Replication

Multiple regions accept writes and replicate them to one another. This can reduce the distance to a write endpoint, but concurrent writes may conflict and write acknowledgment does not by itself define when other regions can read the change.

graph LR
    L1["Leader 1<br/>US-East"] <--> L2["Leader 2<br/>US-West"];
    L2 <--> L3["Leader 3<br/>EU-West"];
    L1 <--> L3;

CouchDB and Cassandra support multi-datacenter replication with product-specific behavior. DynamoDB Global Tables offer multi-Region modes; MREC replicates asynchronously, while MRSC has different consistency and placement requirements. Choose based on the guarantees required and the current service documentation.

Leaderless Replication

In a leaderless design, clients coordinate with replicas directly. Some systems use quorum reads and writes, but the guarantees depend on replica placement, consistency settings, and conflict handling.

graph LR
    Client --> R1["Replica 1<br/>US-East"];
    Client --> R2["Replica 2<br/>US-West"];
    Client --> R3["Replica 3<br/>EU-West"];
    R1 <--> R2;
    R2 <--> R3;
    R3 <--> R1;

This model can avoid dependence on one write leader, but it does not remove failure modes or guarantee a particular latency. Cassandra uses tunable consistency levels. DynamoDB has its own service-defined read and multi-Region consistency options, so it should not be treated as a generic leaderless store.

Consistency and Failover

Consistency vs Latency Trade-offs

Example setting What it means What to verify
Cassandra ONE One replica acknowledges the operation. Whether the selected replica set meets the application’s read-after-write needs and failure model.
Cassandra LOCAL_QUORUM A quorum in the coordinator’s local datacenter acknowledges the operation. Replication strategy, coordinator location, and how remote datacenters are expected to behave.
DynamoDB strong read A regional read returns the latest successful write for supported table and index operations. Strong reads are not supported on global secondary indexes or streams; global table behavior depends on MREC or MRSC mode.

These settings do not form a universal latency ranking. Network distance, item size, contention, replication topology, and service configuration all affect response time.

Conflict Resolution Strategies

When writes can happen in multiple places, something has to decide which one wins:

Last-writer-wins (LWW): Some databases or data models resolve concurrent values using timestamps. Clock assumptions and product behavior matter, and one update can overwrite another. Application-defined: Code applies a domain rule, such as merging independent fields or rejecting an invalid transition. CRDTs: Certain data structures can merge concurrent changes under defined rules, but do not fit every domain. Manual resolution: Send ambiguous conflicts for review when overwriting either value would be unsafe.

# Example: LWW conflict resolution
def resolve_conflict(local_value, remote_value, local_ts, remote_ts):
    return remote_value if remote_ts > local_ts else local_value

Cross-Region Failover Considerations

When an entire region disappears, what happens next depends on your topology:

Single-leader: Follow the product’s configured election or promotion procedure; applications may need to refresh connections or endpoints. Multi-leader: Other regions may continue writes, so plan how concurrent updates are reconciled. Leaderless: Success depends on reachable replicas and the configured consistency level. Rejoining and repair behavior is product-specific.

Consistency Models and Data Modeling

Eventual Consistency vs Strong Consistency

Consistency options differ across products and even between operations on the same product. Define what each read or write must guarantee, then select and test the matching product setting.

flowchart TD
    subgraph "Consistency Spectrum"
        E["Eventual Consistency<br/>Writes propagate async<br/>Reads may return stale data"]
        S["Stronger read/write guarantees<br/>Depend on product and configuration"]
    end
    E -->|requires product-specific settings| S

Eventual consistency means replicas may temporarily disagree after a write. The lag depends on the product, topology, load, and failure conditions; avoid assuming a fixed window.

Read and write guarantees are product-specific. MongoDB’s majority read concern returns majority-committed data under its documented conditions, but it does not make every read linearizable. Transaction guarantees also depend on the transaction’s read and write concerns. Cassandra consistency levels are evaluated against a replication strategy and coordinator. DynamoDB supports eventual and strong reads in a Region for supported operations; global tables offer multi-Region eventual consistency (MREC) and multi-Region strong consistency (MRSC), with different constraints. The names alone are not enough: check the current documentation for the deployed product version or managed-service mode.

CAP theorem describes a trade-off during a network partition between consistency and availability for an operation. It does not label an entire database permanently AP or CP. A useful design question is which reads and writes should succeed when some replicas are unreachable, and what stale or conflicting results the application can handle.

Stale reads in practice: A client writes processed to one replica, then reads pending from another replica before replication catches up. Whether that can happen depends on the database and the chosen read and write settings. For operations that require read-after-write behavior, use a supported guarantee or route subsequent reads appropriately; do not assume that enabling a generic quorum or repair feature solves every consistency requirement.

DynamoDB read consistency: Regional reads can be eventual or strongly consistent on tables and local secondary indexes. Strong reads are not available on global secondary indexes or streams. Global tables use either MREC, the default multi-Region eventual consistency mode, or MRSC, which has stronger guarantees and additional deployment constraints. These choices affect application semantics as well as latency, so evaluate them against the current DynamoDB documentation and benchmark the actual workload.

NoSQL Data Modeling Patterns

Materialized Path Pattern

Store the full path to enable efficient tree traversal.

# MongoDB: Materialized Path
{
  "_id": "electronics/tvs/large-tvs",
  "name": "65 inch TV",
  "path": "/electronics/tvs/large-tvs/",
  "ancestors": ["electronics", "electronics/tvs"]
}

# Query all descendants of electronics
db.categories.find({ path: /^electronics\// })

Tree Structure with Nested Sets

Alternative for read-heavy tree operations.

// Nested set model - efficient subtree reads
{
  "_id": "electronics",
  "left": 1,
  "right": 14
}
{
  "_id": "tvs",
  "left": 2,
  "right": 13
}

Tradeoff: updates require rebalancing the entire tree. Use materialized path for write-heavy workloads.

Document Versioning Pattern

Track change history without schema migrations.

// Current version
{ "_id": "doc-123", "version": 3, "data": {...} }

// Version history (separate collection)
{ "doc_id": "doc-123", "version": 1, "data": {...}, "updated_at": ... }
{ "doc_id": "doc-123", "version": 2, "data": {...}, "updated_at": ... }

Quick Recap Checklist

  • Choose a NoSQL model that fits the application’s access patterns and query needs.
  • Design partition keys to distribute load and avoid hot partitions.
  • Decide how much consistency and replication lag the application can tolerate.
  • Plan sharding, capacity, and recovery around expected growth and failure scenarios.
  • Monitor latency, throttling, replication, storage, and compaction; secure data and credentials.

Observability Checklist

Metrics to Monitor:

Track request latency (p50, p95, p99) by operation type and request throughput (reads/writes per second). Watch node availability and cluster health, disk usage per node and cluster-wide, and network I/O between nodes. Replication lag and pending writes matter for consistency. Compaction progress and queue depth affect performance unpredictably. If you use caching, track cache hit ratios. Connection pool utilization catches exhaustion before it becomes an outage.

Logs to Capture:

Log node failures and restarts, compaction events with I/O patterns, authentication failures and denied permissions. Slow query logs (set a threshold that makes sense for your workload) are essential. For JVM-based systems like Cassandra, GC pauses and heap pressure show up at the worst times. Network partition events are worth capturing for post-mortems.

Alerts to Set:

Alert on node failures, replication lag beyond the application’s tolerance, failed requests, and latency outside the service objective. Set disk and compaction thresholds from the recovery headroom and workload of the specific database. Watch connection pools before saturation causes application requests to queue.

# Example: Cassandra nodetool commands for monitoring
# nodetool status           # Cluster health and node status
# nodetool tpstats          # Thread pool statistics
# nodetool cfstats          # Keyspace and table statistics
# nodetool proxyhistograms  # Client request latency

Security Checklist

  • Enable authentication (internal authentication or external like Kerberos)
  • Implement authorization with role-based access control
  • Encrypt client-to-node and node-to-node traffic
  • Encrypt data at rest (filesystem or application-level encryption)
  • Use TLS for all inter-node communication
  • Restrict network access to database nodes (firewall rules)
  • Implement keyspace-level or table-level permissions
  • Audit log sensitive operations and access patterns
  • Sanitize all user inputs to prevent injection attacks
  • Use secure secret management for database credentials
  • Regularly rotate credentials and encryption keys
  • Test security configuration with penetration testing

Interview Questions

1. What are the main differences between MongoDB and DynamoDB when deciding which to use at scale?
MongoDB's query and aggregation features support a range of query shapes, provided the required indexes and resources are available. DynamoDB works best when important access patterns map to its key and index design. That can make request costs more predictable, but changing a key design may require a data migration or another representation. Compare the specific queries, consistency needs, partitioning behavior, cost model, and operating burden rather than assuming one product is always simpler at a given scale.
2. You are designing a Cassandra keyspace for a messaging application. What partition key would you use and why?
For conversation history, a Cassandra table might use (conversation_id, day_bucket) as its partition key and message_time as a clustering column. That keeps ordered reads within a bounded bucket. A query spanning several buckets must read and combine more than one partition. Choose the bucket size from expected message volume and the application's read window, then check for hot conversations and large partitions under realistic traffic.
3. When would you choose Redis over a disk-based database for a given workload?
Redis can fit session state, rate limits, caches, and leaderboards when the access pattern maps to its data structures and the memory and persistence model meets the application's needs. Benchmark the deployed Redis version, hardware, data sizes, persistence settings, and client path before setting a latency target. For durability, review the selected persistence and replication configuration. For complex filtering or joins, a relational or document database may fit better.
4. Your team is considering a NewSQL database (CockroachDB or TiDB) over PostgreSQL with read replicas. What questions would you ask before making that decision?
Ask which workload is limited: reads, writes, storage, or geographic placement. Read replicas may help a read-heavy PostgreSQL workload, while a distributed SQL system can provide a different write and failure model with transaction semantics. Compare measured latency and throughput on representative workloads, consistency and transaction behavior during failures, rebalancing, deployment topology, and the team's operational experience. There is no fixed latency multiplier that applies across deployments.
5. Explain how consistent hashing works and why it reduces data movement when nodes are added or removed compared to traditional hash-based sharding.
Consistent hashing assigns keys and nodes to positions on a ring, then routes each key to a node responsible for its position. A membership change can remap a subset of ranges instead of recomputing every key with a new modulo divisor. The amount of data moved depends on the ring implementation, virtual-node configuration, and replication policy. Cassandra uses token ranges and virtual nodes in common configurations, but a product's balancing behavior should not be inferred from the abstract hashing algorithm alone.
6. How would you design a partition key for a Cassandra table that stores user activity events to avoid hot partitions while keeping related data co-located?
Start from the common query. For activity history, a Cassandra table could use (user_id, day_bucket) as its partition key and event_time as a clustering column. Bucketing limits growth for active users while supporting time-window reads. If queries span buckets, the application must read and combine them. Check key distribution and partition sizes; low-cardinality keys can concentrate traffic, while the right bucket size depends on the event rate and retention policy.
7. What are the trade-offs between single-leader, multi-leader, and leaderless replication topologies, and when would you choose each?
A single-leader topology centralizes writes and needs a defined failover procedure. Multi-leader designs allow writes in multiple locations, so concurrent updates and replication semantics need explicit handling. Leaderless designs coordinate with replicas according to product-specific settings. Compare guarantees during partitions, conflict handling, regional latency, recovery steps, and operational tooling for the specific database rather than choosing by topology name alone.
8. Describe how you would migrate a large MySQL workload to MongoDB while maintaining application availability during the cutover.
Capture a consistent snapshot from MySQL, then backfill it to MongoDB in batches. Record changes made during the backfill through MySQL binlog-based CDC and apply them idempotently. Verify the target before routing reads to it. Plan how writes are handled during cutover and keep a rollback path until the new workload is stable. Avoid uncoordinated dual writes, which can leave one system updated and the other behind. Check query behavior too: MongoDB's aggregation and index model differs from SQL joins.
9. How does the BASE model differ from ACID, and what types of applications are better suited for each?
ACID describes transaction properties: atomicity, consistency, isolation, and durability. BASE is a loose design shorthand associated with basic availability, soft state, and eventual consistency; neither label tells you which guarantees a particular product provides. For an order or inventory update, identify the invariant and transaction boundary, then check that the database and configuration can enforce them. A feed or cache may tolerate delayed propagation. Some applications use different stores for different operations.
10. Your DynamoDB table is experiencing throttling on a specific partition despite having low overall table utilization. What could be causing this and how would you diagnose it?
A skewed partition key or hot item can concentrate requests even when table-wide utilization is low. Inspect throttling reasons, consumed capacity, key distribution, item sizes, and whether a base table or secondary index is affected. Use the metrics currently exposed for the selected table and capacity mode; partition-level details are not available through every metric. A write-sharded key or cache can distribute eligible reads, but both add application complexity. Adaptive capacity helps with uneven access patterns within DynamoDB's documented limits, not unlimited throughput.
11. What are CRDTs and how do they solve conflict resolution in distributed databases without coordination?
Conflict-free replicated data types (CRDTs) define merge rules that let certain data types converge after concurrent updates. Examples include grow-only counters, last-writer-wins registers, and observed-remove sets. Their guarantees depend on the data type and implementation. A system may accept local writes during a partition and merge them later, but CRDTs do not make every data model conflict-free; counters, sets, and registers are easier to represent than arbitrary linked structures.
12. How would you approach capacity planning for a Cassandra cluster handling 50,000 writes per second with 2TB of data growing at 100GB per day?
Convert the stated operation rate and item sizes into estimated payload and replication traffic, then account for indexes, compaction, repair, retention, and growth. Replication factor affects storage, but write and network overhead also depend on consistency settings, schema, topology, and workload. Benchmark on the intended Cassandra version and hardware, including node loss and repair activity; do not infer node count from a universal writes-per-second figure. Select a compaction strategy for the data lifecycle, and leave enough capacity for the observed background work.
13. Compare the operational complexity of running self-hosted Cassandra versus using a managed service like DataStax Astra or Amazon Keyspaces.
A self-managed Cassandra cluster requires the team to handle capacity, upgrades, repairs, compaction, and recovery. Managed services take over some of that work, but their supported APIs, settings, availability, and pricing differ. Compare the current service documentation and a workload-specific cost estimate, including storage, requests, network, backups, and operational staffing. Choose based on required control and the team's ability to run the system.
14. What monitoring metrics are most critical for detecting impending failures in a MongoDB replica set before they cause downtime?
Monitor replication lag alongside oplog generation and retention, connection pool saturation, disk latency, memory pressure, and operation latency. For WiredTiger, distinguish its configured cache from the filesystem cache and watch cache eviction and disk reads for the workload; the whole dataset does not need to fit in the WiredTiger cache. Set alert thresholds from the service objective and observed normal range, then test the response procedure during a controlled failure exercise.
15. What are the most common causes of data loss in NoSQL databases and how would you prevent or recover from each?
Risk varies by product and setup. Accidental deletion calls for tested backups and point-in-time recovery where supported. Acknowledgment and failover behavior depend on the write concern or consistency level and topology. Disk damage calls for the product's supported recovery procedure; Cassandra repair reconciles replicas, while MongoDB deployments use replica-set recovery and backups. Throttling is an availability problem and does not itself mean acknowledged data was lost. Test restore, failover, and repair procedures for the deployed version rather than assuming one repair command applies across databases.
16. How does the choice between synchronous and asynchronous replication affect consistency, availability, and latency in a distributed database?
Synchronous and asynchronous describe when replication is acknowledged, but products expose the choice through different write concerns, consistency levels, or service modes. An acknowledgment policy does not by itself guarantee that every subsequent read sees the write; read concern, routing, and transaction settings also matter. Waiting for more replicas can affect latency and availability during failures. Compare the exact write and read guarantees and benchmark the deployed topology.
17. What are tombstones in Cassandra, why can they cause problems, and how do you manage them?
Cassandra uses tombstones to record deletions until replica reconciliation and compaction can safely remove the data. Reads over partitions with many relevant tombstones can become more expensive, and purging depends on repair, grace-period, and compaction settings. Model retention to limit unnecessary deletes, choose a compaction strategy that fits the data lifecycle, and follow the deployed Cassandra version's repair and tombstone guidance. MongoDB has different deletion and storage-reclamation behavior, so do not apply Cassandra tombstone advice to it.
18. What should you consider about MongoDB's WiredTiger storage engine when planning memory and latency?
MongoDB uses WiredTiger by default in current self-managed deployments. WiredTiger caches data and indexes and also relies on the operating system's filesystem cache; memory needs depend on the active working set and workload. It uses B-tree indexes, not LSM-tree indexes. An in-memory storage engine is available in MongoDB Enterprise, with its own limitations and configuration requirements. Check the documentation for the deployed MongoDB version and edition, then benchmark memory, disk, and latency behavior before choosing an engine.
19. What is the difference between optimistic locking and pessimistic locking in the context of NoSQL databases? Give an example of when each applies.
Optimistic concurrency control detects a conflicting update when a condition or version check fails; the client then retries or reports the conflict. A MongoDB update can include a version predicate, and DynamoDB supports conditional writes. Redis WATCH/MULTI/EXEC uses optimistic watching of keys, not pessimistic locking. Cassandra lightweight transactions use conditional operations with Paxos and have different costs and guarantees from ordinary writes. Compare each product's conflict behavior and measure contention rather than treating these features as interchangeable lock types.
20. What is the "dual write" problem in distributed databases, and how do you solve it when migrating between data stores or maintaining multiple data sources?
A dual write can succeed in one system and fail in another, leaving them inconsistent. Change-data capture or a transactional outbox can make updates recoverable, but delivery is usually at least once and consumers need idempotency or deduplication. An outbox places the source update and event record in one local transaction; it does not make the downstream update part of that transaction. Add reconciliation and retry handling for the full pipeline.

Further Reading

Official Documentation

Consistency and operations references

Books

  • “Designing Data-Intensive Applications” by Martin Kleppmann — The definitive text on distributed systems and data storage trade-offs
  • “Cassandra: The Definitive Guide” by Jeff Carpenter and Eben Hewitt — Practical Cassandra operations and modeling
  • “MongoDB Applied Design Patterns” by Rick Copeland — Document modeling patterns for common use cases

Papers and References

Conclusion

Choose the database model from the queries and guarantees the application needs. Key-value stores fit exact-key access; document stores group records commonly read together; wide-column stores need bounded partitions designed around known queries; graph stores suit relationship traversals. Those model labels do not promise a particular latency or scale.

For critical operations, verify transaction, consistency, and failover behavior for the specific product and configuration. Then compare partitioning, recovery work, and operational load with a relational design. Relational constraints and transactions may be the safer starting point when business invariants span related records.

Copy/Paste Checklist:

# MongoDB connection with monitoring
from pymongo import MongoClient
client = MongoClient("mongodb://user:pass@host:27017/?replicaSet=rs0")
db = client.admin
# Check replica set status
print(db.command('replSetGetStatus'))

# Cassandra connection with monitoring
from cassandra.cluster import Cluster
cluster = Cluster(['host1', 'host2', 'host3'])
session = cluster.connect('mykeyspace')
# Check cluster health
session.execute("SELECT * FROM system.local")
session.execute("SELECT * FROM system.peers")

# Redis security and monitoring
redis-cli INFO clients  # Client connections
redis-cli INFO stats     # Command statistics
redis-cli CONFIG GET *   # Configuration audit

Category

Related Posts

Amazon DynamoDB Data Modeling: Start with Access Patterns

Design DynamoDB tables from concrete access patterns with a worked orders example, a global secondary index, capacity estimates, and a throttling failure.

#dynamodb #databases #nosql

DynamoDB Operations: Capacity, Backups, and Recovery

Choose a DynamoDB capacity mode, diagnose throttling, and plan backup and recovery steps with current AWS guidance for your workload.

#dynamodb #aws #operations

Column-Family Databases: Cassandra and HBase Architecture

Cassandra and HBase data storage explained. Learn partition key design, column families, time-series modeling, and consistency tradeoffs.

#database #nosql #column-family