Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 30 ยท Interviews and Cheat Sheet

Interview questions and answers

Prepare for Cassandra and Neo4j interviews: CAP, partitioning, consistency, compaction, tombstones, Cypher patterns and modeling, with model answers.

Interviewers for data roles tend to ask the same kinds of questions: explain a concept briefly, compare two designs, find the flaw in a model, and reason about a failure. This lesson collects the questions that come up most for Cassandra and Neo4j, with answers written the way you could say them out loud in about a minute. Each answer starts with the short version and then adds the detail that shows you understand it.

Use the lesson as a rehearsal. Cover the answer, say yours aloud, then compare. Two stand-ins in the middle let you re-create the trickiest ideas (quorum overlap and tombstones) in your browser, because explaining them with real numbers is much more convincing than reciting a definition. The databases themselves cannot run on this site, so code in blocks is read-only, and the stand-ins are small simulations of the ideas.

Fundamentals

What is the difference between Cassandra and a relational database?

Cassandra is a distributed, wide-column store that spreads data across many equal nodes. Rows are placed by a hash of the partition key, there is no master, and you design one table per query because there are no joins. A relational database centers on a normalized schema, joins and multi-row transactions, usually on one primary server. In short: Cassandra trades flexibility and strong transactions for write scalability and availability. See Cassandra architecture in one picture.

Explain the CAP theorem in plain language.

When a network partition splits a distributed system, it has to choose between consistency (every read sees the latest write, or fails) and availability (every request gets an answer, possibly an older one). Partition tolerance is not optional in a real network, so the real choice is C or A during a partition. Cassandra is usually described as favoring availability, but it is tunable: with QUORUM reads and writes it behaves much more consistently, at the cost of becoming unavailable when too many replicas are down. PACELC adds that even without a partition there is a trade between latency and consistency. Be careful not to say "Cassandra is AP" as if it were fixed. It depends on the levels you choose.

What is a partition key, and what is a clustering key?

The partition key decides which nodes store a row: it is hashed to a token, and the token picks the replicas. The clustering columns decide the order of rows inside a partition. In PRIMARY KEY ((user_id, day), ts) the partition key is (user_id, day) and ts is the clustering column. Queries must supply the whole partition key, and clustering columns can then narrow the slice. See Partition keys and clustering keys.

What is the replication factor, and how is it different from the consistency level?

The replication factor (RF) is a property of the keyspace: how many nodes store a copy of each row. The consistency level (CL) is a property of one request: how many of those replicas must respond before the request is considered successful. RF is a storage decision, and CL is a per-operation choice about latency and certainty.

What does "tunable consistency" mean, and what is the R + W > RF rule?

You pick the consistency level for each read and write. If the number of replicas that must acknowledge a write (W) plus the number that must answer a read (R) is greater than the replication factor, then every read set overlaps every write set, so a read includes at least one replica with the latest value and returns it by timestamp. With RF 3, QUORUM (2) for both gives 4 > 3. The stand-in below prints that table for RF 3 and RF 5.

JS Which read and write levels overlap?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two readings to point out in an interview: ONE with ALL overlaps, and ALL on reads or writes survives zero failures for that operation. The last number is the minimum of the two operations' tolerance, a deliberately simple measure. In practice LOCAL_QUORUM in a multi-datacenter cluster is the common pairing.

Write path, reads and storage

Why are Cassandra writes fast?

A write is appended to the commit log (sequential disk I/O, for durability) and put into an in-memory memtable. No existing file is modified in place and no read-before-write is needed. Later the memtable is flushed to an immutable SSTable. See The write path.

What happens on a read?

The coordinator asks the replicas required by the consistency level. Each replica merges the memtable and every SSTable that might hold the partition. Bloom filters skip SSTables that definitely do not contain the key, and the newest timestamp wins for each column. If replicas disagree, the coordinator returns the newest and triggers read repair. More in The read path, bloom filters and compaction.

What is compaction, and which strategies exist?

Compaction merges SSTables to drop overwritten data and expired tombstones and to keep read amplification down. STCS (size-tiered) merges similarly sized files and favors write-heavy loads; LCS (leveled) keeps data in levels with few overlapping files and favors read-heavy loads at the cost of more write I/O; TWCS (time-window) groups data by time and suits TTL'd time-series. The right choice follows the access pattern.

What is a tombstone, and why can it hurt?

Because SSTables are immutable, a delete cannot erase data. Cassandra writes a tombstone marker with a timestamp that shadows older data. Tombstones are kept for gc_grace_seconds so every replica learns about the delete, and then compaction can purge them. They hurt when queries scan many of them (a queue-like table, or a partition with many deleted rows): the read must process them all. Deleting data also leaves it on disk until compaction.

The classic follow-up is "what is zombie data?". The stand-in below shows the failure: a replica that missed the delete gets the old value back after the tombstone was purged elsewhere.

Python A tombstone, a missed delete and a zombie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the lesson in the last line: the safety of deletes depends on running repair more often than gc_grace_seconds. A good interview answer names that operational rule. See Deletes, TTL and tombstones.

Why does a wide partition cause problems?

A partition lives on one set of replicas, is read as a unit by some operations, and is compacted and repaired as a unit. A very large partition causes hot nodes, long garbage-collection pauses, slow reads and stuck repairs. The cure is bucketing the key (add a time bucket or another dimension) so each partition stays bounded.

Modeling and practice

How do you model data in Cassandra?

Start from the queries. For each query choose a partition key you can supply, add clustering columns for ordering, and include the columns the query returns. Duplicate data across tables on purpose. See Query-first data modeling.

Why are secondary indexes and ALLOW FILTERING discouraged?

A traditional secondary index is local to each node, so a query without the partition key has to ask many nodes. ALLOW FILTERING lets a query read and discard rows, and its cost grows with the data. They are acceptable for low-cardinality columns combined with a partition key, or on small tables. For general use, create another query table instead. Newer index implementations improve this but still do not remove the cost of scatter-gather. See Secondary indexes, SAI and materialized views.

What is a lightweight transaction, and when would you use one?

A conditional write (INSERT ... IF NOT EXISTS, UPDATE ... IF col = value) that uses Paxos to give linearizable compare-and-set on one partition. Use it for rare cases like claiming a unique username. It costs several round trips, so never use it on a hot path. See Lightweight transactions, batches and counters.

Are batches a performance feature?

No. A logged batch gives atomicity (all the statements eventually apply) across partitions at the cost of extra coordination. A batch to a single partition is cheap and atomic and isolated. Large multi-partition batches put pressure on the coordinator. Use batches for correctness, not speed.

Neo4j and Cypher

What is the property graph model?

Nodes (with labels and properties) connected by directed, typed relationships (which can also have properties). It is "native" in that relationships are stored as direct pointers, so following one does not require an index lookup or a join. See Neo4j and the property graph model.

What is the difference between CREATE and MERGE?

CREATE always makes a new node or relationship. MERGE matches the whole pattern, and creates it only if it does not exist. Use MERGE for imports you may repeat, with uniqueness constraints on the key properties; use ON CREATE SET and ON MATCH SET to control which properties are written. See Cypher: MERGE, SET, DELETE and constraints.

How would you find friends of friends who are not already friends?

CYPHER
MATCH (me:User {name: $name})-[:FRIEND]-(f)-[:FRIEND]-(fof)
WHERE fof <> me AND NOT (me)-[:FRIEND]-(fof)
RETURN fof.name, count(DISTINCT f) AS mutual
ORDER BY mutual DESC;

The pattern walks two hops, the WHERE removes yourself and existing friends, and count(DISTINCT f) counts mutual friends once each. Mention the parameter $name, which keeps the query plan reusable and avoids injection. See Paths, aggregation and WITH.

What does WITH do?

WITH ends one query stage and starts the next, passing on only the variables you name. It is how you aggregate and then filter on the result (the equivalent of HAVING), limit intermediate rows, or reshape data before the next MATCH.

How do you find the shortest path, and what is the danger of unbounded paths?

Use shortestPath((a)-[*..N]-(b)) or allShortestPaths. An unbounded variable-length pattern such as [*] on a well-connected graph can explode, because the number of paths grows very fast, so always bound the length and start from indexed nodes.

When is a graph database a bad choice?

When the data has few relationships, when queries are bulk aggregations over everything, or when you need a huge write rate of simple records. See Cassandra, Neo4j, or something else?.

How do you tune a slow Cypher query?

Use EXPLAIN to see the plan without running it and PROFILE to run it and count db hits. Make sure the starting MATCH uses an index on a selective property, avoid cartesian products (two disconnected patterns), filter early, and use parameters. This is covered in Query performance: indexes, EXPLAIN and PROFILE.

Scenario questions

Interviewers like open scenarios. A structure that works for any of them:

  1. Restate the requirement and ask about the scale and the main queries.
  2. State the queries, then the model (keys, labels, relationships).
  3. Name the trade-offs (what the design cannot answer, what it costs on writes).
  4. Address failure (a node dies, a partition grows, a message is retried).
  5. Finish with how you would measure it: partition sizes, latency percentiles, db hits.

Some prompts to practice with: design a chat history; count unique visitors per page; detect accounts that share devices; recommend products from purchase history; store sensor data for ten years.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about CAP and Cassandra is the most accurate?

    With tunable consistency, low levels favor availability and quorum levels give stronger consistency but less tolerance of failures.
  2. 2. What must happen to avoid zombie data after a delete?

    If a replica never receives the tombstone and the tombstone is purged elsewhere, the old value can be repaired back into the cluster.
  3. 3. In Cypher, what is the main difference between CREATE and MERGE?

    MERGE matches first and creates only the missing pattern, which makes loads repeatable.
  4. 4. Why are batches not a performance feature in Cassandra?

    Logged batches exist for atomicity across statements. Large multi-partition batches strain the coordinator.
  5. 5. Which compaction strategy is usually best for TTL'd time-series data?

    Time-window compaction groups data by time so whole expired windows can be dropped together.

Summary

  • Answer each question with a one-sentence version first, then the detail that proves understanding.
  • Know the quorum overlap rule (R + W > RF), the write path (commit log, memtable, SSTable) and the three compaction families.
  • Explain tombstones together with gc_grace_seconds and repair, or you will miss the zombie-data point.
  • For Cassandra modeling, start from queries; for Neo4j, use MERGE, constraints, bounded paths and PROFILE.
  • In scenario questions, state the queries, the model, the trade-offs, the failure behavior and how you would measure.

Next: Cassandra and Neo4j cheat sheet.