ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume IV
  5. Categories
Book 6 · Volume IV — NoSQL, Caching & Polyglot Persistence · Topic 1.2

Categories

Key-value, document, wide-column and graph

9 min readStage 3 · Systems8 interview questions
Chapter
Chapter 1 — NoSQL Fundamentals
Prerequisites
Topic 1.1
You will be able to
Describe the four NoSQL data models precisely, explain how each stores and retrieves data, identify their natural access patterns and limitations, recognise multi-model products, and choose a category from a workload description
Covers
Key-value; Document; Wide-column; Graph
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Storage and Distribution by Category
  5. 4A. Deep Dive — Multi-Model Databases and Blurred Boundaries
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

NoSQL databases are classified by their data model — the shape in which data is stored and accessed.

The four NoSQL categories
Figure 1 — The four NoSQL categories
CategoryData modelPrimary accessExamples
Key-valueKey → opaque valueGet/put/delete by keyRedis, DynamoDB, Riak, etcd
DocumentKey → structured, nested document (JSON/BSON)By id + queries on fieldsMongoDB, Couchbase, Firestore
Wide-columnPartition key → sorted rows with many columnsPartition + clustering-key rangesCassandra, HBase, Bigtable, ScyllaDB
GraphNodes + relationships with propertiesTraversals, pattern matchingNeo4j, Neptune, Memgraph
Table 1 — Four categories

2Why It Exists

The relational model is general: any query over any combination of tables. Specialised models give up some generality to gain performance, scalability or expressiveness for particular patterns. Classifying stores by model helps architects reason about capabilities independent of product marketing.

Data model spectrumMore structure visible to the database →
Key-valueValue opaque; database knows only keys
Wide-columnDatabase knows partition/clustering keys and columns
DocumentDatabase understands nested fields and indexes them
GraphDatabase understands entities and their relationships
Table 2 — How much the database "understands"

3Core Concepts

3.1 Key-value

Key-value model
Figure 2 — Key-value model
PropertyDetail
OperationsGET, SET/PUT, DELETE, often atomic increments, TTL, conditional put
ComplexityO(1) lookups by hash; distribution by key hash
ValueOpaque bytes (Redis adds rich data structures: hashes, lists, sets, sorted sets, streams)
StrengthsLatency (sub-ms in memory), simplicity, linear scale
LimitsNo queries on value content; secondary access needs extra keys/indexes
Table 3 — Key-value characteristics
JAVA
// Spring Data Redis: session-like data with TTL
redis.opsForValue().set("session:" + sid, sessionJson, Duration.ofMinutes(30));
String s = redis.opsForValue().get("session:" + sid);
Long hits = redis.opsForValue().increment("rate:ip:" + ip);    // atomic counter

3.2 Document

Document model
Figure 3 — Document model
PropertyDetail
UnitSelf-contained document (nested objects, arrays), typically ≤ 16 MB (MongoDB)
OperationsCRUD by id, queries on any field, secondary indexes, aggregation
AtomicitySingle-document writes atomic; multi-document transactions optional
StrengthsMatches application objects; flexible structure; rich queries
LimitsCross-document joins costly; duplication to manage
Table 4 — Document characteristics
JAVA
Query q = Query.query(Criteria.where("status").is("PAID").and("customer.id").is(17))
               .with(Sort.by(Sort.Direction.DESC, "placedAt")).limit(20);
List<OrderDoc> orders = mongo.find(q, OrderDoc.class);

3.3 Wide-column

Wide-column model
Figure 4 — Wide-column model
PropertyDetail
StructureTable → partitions (partition key) → rows sorted by clustering columns
StorageLog-structured merge (LSM) trees: commit log, memtable, SSTables, compaction
OperationsWrites anywhere (fast), reads by partition key + clustering range
StrengthsMassive write throughput, linear scale, multi-datacenter replication
LimitsQueries must follow key design; no joins; limited ad-hoc filtering
Table 5 — Wide-column characteristics
SQL
-- CQL (Cassandra): table designed for one query
CREATE TABLE readings_by_sensor_day (
  sensor_id text, day date, ts timestamp, value double,
  PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC);
 
SELECT ts, value FROM readings_by_sensor_day
 WHERE sensor_id = 'S-42' AND day = '2026-09-25' AND ts >= '2026-09-25 08:00:00';

3.4 Graph

Graph model
Figure 5 — Graph model
PropertyDetail
StructureNodes (labels, properties), relationships (type, direction, properties)
StorageIndex-free adjacency — each node points to its relationships
OperationsPattern matching and traversals (Cypher, Gremlin, GQL)
StrengthsMulti-hop queries in time proportional to the traversed subgraph
LimitsHorizontal write scaling harder; bulk scans/aggregations weaker than columnar/analytic stores
Table 6 — Graph characteristics
TEXT
// Cypher: accounts sharing a device with a known fraudster (2 hops)
MATCH (f:Customer {flagged: true})-[:USES]->(d:Device)<-[:USES]-(c:Customer)
WHERE c <> f
RETURN DISTINCT c.id, d.id

4How It Works Internally — Storage and Distribution by Category

CategoryTypical storage engineDistribution
Key-value (Redis)In-memory hash tables + optional persistence (RDB/AOF)Hash slots (16,384) across masters
Key-value (DynamoDB)B-tree/LSM on SSD per partitionHash of partition key
Document (MongoDB)WiredTiger B-trees, compressedReplica sets; sharding by shard key (range/hash)
Wide-column (Cassandra)LSM: commit log, memtable, SSTablesConsistent hashing token ring, vnodes
Graph (Neo4j)Native record stores with adjacency pointersLeader + followers; sharding via composite databases
Table 7 — Under the hood

4ADeep Dive — Multi-Model Databases and Blurred Boundaries

ProductPrimary modelAdditional models
PostgreSQLRelationalDocument (JSONB), key-value (hstore), graph (Apache AGE extension), vector (pgvector)
MongoDBDocumentTime series collections, search, vector search
RedisKey-valueJSON documents, search, time series, vectors
Azure Cosmos DBMulti-APIDocument, key-value, wide-column (Cassandra API), graph (Gremlin)
CouchbaseDocumentKey-value first access, SQL++ queries
Table 8 — Categories describe models, products increasingly combine them
NoSQL categories compared
Figure 6 — NoSQL categories compared

A multi-model product reduces the number of systems but each secondary model is usually less mature than a specialised store — evaluate the model you actually need.

5APIs / Features / Syntax

CategorySpring Data moduleRepository example
Key-valueSpring Data Redis@RedisHash("carts") record Cart(...) + CrudRepository
DocumentSpring Data MongoDBMongoRepository<OrderDoc, String>
Wide-columnSpring Data CassandraCassandraRepository<Reading, ReadingKey>
GraphSpring Data Neo4jNeo4jRepository<Customer, Long> with @Query Cypher
Table 9 — Same Spring Data programming model, different semantics

6Practical Examples

6.1 Key-value store used for queries

A team stored customer profiles in Redis as JSON strings and later needed "all customers in Pune with GOLD tier". Without secondary indexes they scanned all keys (SCAN + deserialise), blocking the instance at peak. Moving profiles to a document store (or adding a search index) matched the new access pattern.

6.2 Cassandra table designed like a relational table

A users table with PRIMARY KEY (user_id) was queried WHERE email = ? using ALLOW FILTERING — a full cluster scan. Creating a second table users_by_email (query-first design) fixed it.

6.3 Worked example — one domain in four models

ModelRepresentation of "customer 17 placed order 5001 with 2 lines"
Key-valueorder:5001 → serialised blob; customer:17:orders → list of ids
Documentorders document with embedded lines and customer snapshot
Wide-columnorders_by_customer partition 17, rows clustered by placed_at (one row per order)
Graph(:Customer {id:17})-[:PLACED]->(:Order {id:5001})-[:CONTAINS {qty:2}]->(:Product)
Table 10 — The same facts shaped for different questions

6.4 Worked example — matching access patterns to categories

Access patternCategory
"Get cart for session X" 50 k/s, expires in 2 hKey-value
"Show product page with all attributes and top reviews"Document
"Last 24 h of readings for device D" at 1 M writes/sWide-column
"Which accounts are within 3 hops of this flagged account?"Graph
"Revenue by region and month with ad-hoc filters"Relational / analytical
Table 11 — Choose by the question asked most often

6.5 Worked example — Redis data structures beyond plain values

StructureCommand examplesUse
HashHSET cart:9 sku-1 2Object with fields
Sorted setZADD leaderboard 1820 user:17Rankings, time-ordered indexes
List/StreamLPUSH, XADD events * …Queues, event logs
SetSADD online users:17Membership, deduplication
HyperLogLogPFADD visitors:2026-09-25 u17Approximate unique counts
Table 12 — "Key-value" stores can be data-structure servers

6.6 Worked example — document store for a CMS

JAVA
@Document("articles")
public record Article(@Id String id, String slug, String title,
                      List<Block> body, List<String> tags,
                      Map<String, String> seo, Instant publishedAt) { }
 
public interface ArticleRepository extends MongoRepository<Article, String> {
    Optional<Article> findBySlug(String slug);
    List<Article> findTop10ByTagsContainingOrderByPublishedAtDesc(String tag);
}

Heterogeneous content blocks (text, image, video, quote) fit naturally into an array of polymorphic sub-documents.

6.7 Worked example — wide-column for messaging

QueryTablePrimary key
Messages in a conversation, newest firstmessages_by_conversation((conversation_id), sent_at DESC, message_id)
Conversations of a user by last activityconversations_by_user((user_id), last_activity DESC, conversation_id)
Table 13 — One table per query; writes go to both tables

6.8 Worked example — graph for recommendations

TEXT
MATCH (u:Customer {id: $id})-[:BOUGHT]->(:Product)<-[:BOUGHT]-(other:Customer)
      -[:BOUGHT]->(rec:Product)
WHERE NOT (u)-[:BOUGHT]->(rec)
RETURN rec.sku, count(*) AS score
ORDER BY score DESC LIMIT 10

"Customers who bought what you bought also bought…" is a two-hop pattern expressed directly.

6.9 Worked example — category limits discovered late

CategoryLimit discoveredTypical workaround
Key-valueNeed to query by value attributesSecondary key structures, search index
DocumentMany-to-many reporting across collectionsAnalytics pipeline to warehouse
Wide-columnNew query not supported by key designNew table + backfill
GraphBulk aggregations over all nodesExport to analytics engine
Table 14 — Know the limits before committing

6.10 Worked example — scoring categories for a use case

Criterion (IoT platform)Key-valueDocumentWide-columnGraph
Write rate 500 k/s◆◆✔✘
Range reads by device/time✘◆✔✘
Multi-region✔◆✔◆
TTL expiry✔✔✔◆
Result——Choose—
Table 15 — Structured comparison for one workload

6.11 Worked example — access from one Spring Boot service

YAML
spring:
  data:
    mongodb.uri: mongodb://catalog-db:27017/catalog
    redis: { host: cache, port: 6379 }
  cassandra:
    contact-points: cass-1:9042,cass-2:9042
    keyspace-name: telemetry
    local-datacenter: dc1

Several stores in one service are possible, but each adds connection management, health checks and failure modes — Chapter 7 discusses when this is justified.

6.12 Worked example — time series in a document store

DesignDocuments for 1 device, 1 day, 10 s interval
One document per reading8,640 documents
Bucket pattern: one document per hour with array of readings24 documents
MongoDB time series collectionInternally bucketed and compressed automatically
Table 16 — Document stores can serve time series with the right model

7Common Problems & Mistakes

  • Querying key-value stores by value.
  • Relational thinking in wide-column stores (ALLOW FILTERING).
  • Graph databases for bulk analytics.
  • Document stores for highly relational, cross-entity reporting.
  • Choosing by product popularity instead of model fit.
  • Ignoring multi-model maturity differences.

8Performance & Production Considerations

CategoryKey production concern
Key-valueMemory sizing, eviction, persistence settings
DocumentIndex design, document size, shard key
Wide-columnPartition size, compaction, repairs, tombstones
GraphMemory for graph cache, query depth limits
Table 17 — Operational focus per category

9Architecture & Design Considerations

  • List access patterns first, then choose the model.
  • Expect different data shapes of the same domain in different stores.
  • Prefer fewer stores unless a workload clearly needs a specialised model.
  • Revisit when new access patterns emerge that the chosen model handles poorly.

10Interview Questions & Answers

Q1L1 · BasicConcept

What are the four main NoSQL categories?

The four main categories, classified by data model, are key-value, document, wide-column and graph. Key-value stores such as Redis and DynamoDB map a key to an opaque value and are accessed by key. Document databases such as MongoDB and Couchbase store nested JSON or BSON documents and can index and query fields inside them. Wide-column stores such as Cassandra, HBase, Bigtable and ScyllaDB organise data by partition key into sorted rows that are read by key and clustering-key range. Graph databases such as Neo4j and Neptune store nodes and relationships and answer traversal queries. Each category is optimised for a different access pattern, so classify by model, not product.

Q2L1 · BasicConcept

What is a key-value database best at?

A key-value database is best at very fast, simple operations by key: get, put, delete, atomic increments and conditional writes, often with a time-to-live. Because lookups are hash-based and data is distributed by key, latency is low, sub-millisecond for in-memory stores like Redis or Valkey, and throughput scales almost linearly by adding nodes. Typical uses are HTTP sessions, caches, rate-limit counters, feature flags, idempotency keys and shopping carts. Redis also offers hashes, sorted sets and streams, so it covers leaderboards and simple queues too. The limit is that the store cannot query by value content; any second access path needs extra keys or a different store.

Q3L2 · IntermediateTrade-off

How does a document database differ from a key-value store?

The difference is how much the database understands about the value. In a key-value store the value is opaque bytes: the database can fetch it by key, but it cannot filter, index or partially update fields inside it. A document database parses the document, JSON or BSON, and understands its nested fields and arrays. You can create secondary indexes on fields, query by them, project only some fields, update one field atomically and run aggregation pipelines. So finding all customers in Pune with GOLD tier is an indexed query in MongoDB but a full scan or a hand-built index in Redis. The cost is more storage and CPU per operation than a pure key lookup.

Q4L2 · IntermediateConcept

What is a wide-column database designed for?

A wide-column database is designed for very high write throughput and predictable reads at large scale, when queries follow a known partition key. Data is grouped into partitions by a partition key, distributed across the cluster by hash, and within a partition rows are sorted by clustering columns. Writes go to a commit log and memtable and are flushed to immutable SSTables in an LSM tree, so writes are cheap and sequential. Reads are efficient for one partition plus a clustering range, such as the readings for one sensor on one day, newest first. Typical uses are time series, IoT telemetry, messaging inboxes and activity feeds spread across many nodes and data centres.

Q5L3 · Senior EngineerTrade-off

When is a graph database the right choice?

A graph database is the right choice when the important questions are about connections, especially variable-length, multi-hop paths: friends of friends who bought this product, rings of accounts sharing devices in fraud detection, or which services are affected if this component fails. Graph stores keep relationships as first-class, directly linked records, so each traversal step follows a pointer instead of performing a join, and cost depends on the part of the graph visited, not total table size. In SQL the same questions need many self-joins or recursive CTEs that slow down quickly with depth. It is not the right choice for bulk aggregations or simple CRUD; there a relational store is simpler.

Q6L3 · Senior EngineerInternals

Why do Cassandra tables follow a query-first design?

Because Cassandra can only read efficiently by partition key and, within a partition, by clustering-column order. There are no joins, and filtering on other columns means scanning the cluster, which is what ALLOW FILTERING asks for. So you start from each query and design a table whose primary key makes that query a single-partition read, for example PRIMARY KEY ((sensor_id, day), ts) for readings by sensor and day. If you also need to find users by email, you create a users_by_email table and write to both tables. Denormalisation and duplicate writes are the accepted price; the benefit is predictable latency at any scale. Partition size must stay bounded too.

Q7L4 · Technical ArchitectTricky

What are multi-model databases and what should you watch for?

Multi-model databases support more than one data model in one product: PostgreSQL with jsonb for documents, MongoDB with graph lookups and time-series collections, Azure Cosmos DB with several APIs, or ArangoDB combining documents and graphs. They can reduce the number of systems to operate, secure and keep consistent. The thing to watch is that the secondary models are usually less mature than a specialised store: a graph traversal over documents may lack index-free adjacency, query-language features or performance at depth. So evaluate the specific capability with your real access patterns and data volumes, not the vendor's feature checklist, and check the operational limits before committing to it.

Q8L5 · Solution ArchitectDesign

How do you pick a NoSQL category for a new system?

I begin by enumerating the access patterns: each read and write, its volume, latency target, consistency requirement and growth. Then I map patterns to models: lookups by key with TTL suggest key-value, whole aggregates queried by fields suggest document, high write rates read by partition and time range suggest wide-column, and multi-hop relationship questions suggest graph. I check each candidate's limits against the full list, for example missing secondary indexes or weak cross-partition transactions, and include operational cost, managed-service options and team skills. Often the relational database still serves most patterns. I choose the smallest set of stores that serves them all and record the decision in an ADR.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.