Data Modeling
Build a notification data model from requirements, real records and queries; compare storage families and defend its failure behavior.
What, why, when and how
What is it?
Data modeling defines entities, identities, relationships, constraints and access paths for the operations a product must support.
Why is it needed?
A storage product alone cannot prevent invalid relationships, make an unbounded query cheap, or define which record owns a business fact.
When should I use it?
Use it before choosing storage and revisit it when query patterns, ownership, retention or scale change.
When should I choose something else?
Avoid denormalizing every field or choosing a database before listing the queries. Keep a relational baseline when joins and local transactional constraints fit.
How do I use it?
List concrete reads and writes, identify authoritative records, define keys and invariants, then select indexes or projections. Evaluate alternative storage models using the same operations.
Can you show a concrete example?
For a school notice, keep notice identity and status separate from recipient delivery attempts. A query for recent notices needs a bounded index; it should not load every recipient payload just to list notice titles.
Read the diagram
List request: latest 20 notices for district d7; Read: notice ID, title and status; Recipient payloads stay off the list path
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
Data modeling turns a product requirement into records that can be found, changed and kept correct. A box called “database” does not yet explain how a retry avoids a duplicate, how an inbox finds its newest items, or what happens when one customer grows much larger than the others. A useful model makes those operations visible.
We will model a multi-tenant notification product. A school creates a notice, selects recipients, sends through their chosen channels and displays delivery history. This example lets us follow the same facts through relational tables, documents, key-value records, wide-column partitions and graph relationships. These are alternative representations to evaluate; the finished design does not need all five databases.
What you should be able to explain
By the end, you should be able to draw entities and relationships; distinguish identity, business uniqueness and lookup keys; write a query and an index that supports it; decide what can be embedded or duplicated; and explain how a model behaves under retries, skew, deletion and schema changes. Read the schema first, then predict the result of each operation before reading its explanation.
1. Turn the requirements into questions
Assume each school belongs to a tenant. A tenant must not read or reference another tenant's records. One notice may target 10,000 recipients, and each recipient may receive email, SMS or a call. Numbers here are exercise assumptions, not measured production limits. The dashboard may lag by a few seconds; consent and duplicate prevention require an authoritative decision.
The product asks four different questions:
| Product operation | Data needed | Correctness requirement |
|---|---|---|
| Open a recipient's inbox | Latest 20 deliveries within a tenant | Stable ordering and a bounded page |
| Investigate one delivery | Its notice and every provider attempt | Preserve earlier failures and unknown outcomes |
| Expand a notice into deliveries | One recipient/channel intent per notice | A repeated expansion must not create another intent |
| Dispatch a queued SMS | Current preference for that recipient/channel | An old audience snapshot cannot authorize sending |
These questions determine the records we need. An inbox is a query over deliveries, an investigation is a query over attempts, and dispatch is a decision using live preference state. Putting everything into one campaign JSON object hides these distinctions and makes the object grow with the audience.
Before choosing a store, also ask how many records grow per day, which records are updated together, how long history remains, and whether a tenant dominates the workload. “Millions of users” alone does not tell you whether an index, a cache, another replica or sharding is required.
2. Separate entities by identity and lifetime
A notice is the business intent: “send the attendance reminder using template version 8.” A recipient is a person within a tenant. A delivery is one intended notice/recipient/channel outcome. An attempt is one interaction with a provider. A preference is the recipient's current permission for a channel.
A retry changes the attempt history, not the identity of the intended delivery. A template edit changes future notices or template versions, not the text already selected for a historical send. A preference update changes what may be sent now, not who was originally selected.
Read the diagram
A delivery references one notice and one recipient; an attempt belongs to that delivery. Read the key fields before following the relationship labels.
In a relational model, one notice has many deliveries (1:N), and one delivery has many attempts (1:N). Notices and recipients have a many-to-many relationship through delivery: a recipient receives many notices, and a notice reaches many recipients. The connecting record carries its own facts—channel and state—so it deserves a name and a key.
A recipient/channel pair has one current preference record. If we also need preference history, we add versioned history records rather than turning the current row into an unbounded list. A one-to-one extension can be useful for optional or sensitive profile data with different access controls; it is not automatically a modeling mistake.
Use stable system identities. An email address can change or be shared and should not silently become the person's primary key. A UUID can provide identity, but does not by itself make “newest deliveries for this recipient” efficient. Identity, uniqueness and access order are separate decisions.
3. Build a relational baseline you can reason about
For this workload, a relational store is a reasonable baseline: the core relationships are clear and duplicate prevention needs a write-time constraint. We choose PostgreSQL for the example. That is a justified starting point, not a claim that SQL always wins.
Here are representative rows. All IDs are scoped by tenant t1.
| notice_id | template_version | selected_at |
|---|---|---|
| n40 | 8 | 2026-10-11 09:00 UTC |
| n41 | 8 | 2026-10-11 09:02 UTC |
| recipient_id | display_name |
|---|---|
| r7 | Mira |
| r8 | Omar |
| delivery_id | notice_id | recipient_id | channel | state |
|---|---|---|---|---|
| d91 | n40 | r7 | sms | pending_receipt |
| d92 | n40 | r8 | sms | queued |
| d93 | n41 | r7 | sms | queued |
| delivery_id | attempt_no | provider_ref | outcome |
|---|---|---|---|
| d91 | 1 | p101 | rejected |
| d91 | 2 | p102 | accepted |
The second attempt was made after a definite rejection, under the retry policy. Provider acceptance does not prove recipient delivery, which is why d91 remains pending_receipt. A timeout would instead be unknown; reconcile that attempt or reuse a supported provider idempotency key before risking another external effect.
Primary keys, foreign keys and constraints
A primary key identifies one row. A foreign key requires a reference to an existing parent. A unique constraint expresses business uniqueness even if the table also has a separate primary key. A check constraint rejects invalid values within the row, and NOT NULL requires a value rather than leaving its meaning ambiguous.
This executable SQL is deliberately a small teaching schema. It omits authentication, outbox publication and full provider-state transitions; those contracts are explained below rather than implied by the table definitions.
CREATE TABLE notice (
tenant_id TEXT NOT NULL,
notice_id TEXT NOT NULL,
template_version INTEGER NOT NULL CHECK (template_version > 0),
selected_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (tenant_id, notice_id)
);
CREATE TABLE recipient (
tenant_id TEXT NOT NULL,
recipient_id TEXT NOT NULL,
display_name TEXT NOT NULL,
PRIMARY KEY (tenant_id, recipient_id)
);
CREATE TABLE delivery (
tenant_id TEXT NOT NULL,
delivery_id TEXT NOT NULL,
notice_id TEXT NOT NULL,
recipient_id TEXT NOT NULL,
channel TEXT NOT NULL CHECK (channel IN ('email', 'sms', 'call')),
state TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (tenant_id, delivery_id),
UNIQUE (tenant_id, notice_id, recipient_id, channel),
FOREIGN KEY (tenant_id, notice_id)
REFERENCES notice (tenant_id, notice_id),
FOREIGN KEY (tenant_id, recipient_id)
REFERENCES recipient (tenant_id, recipient_id)
);
CREATE TABLE attempt (
tenant_id TEXT NOT NULL,
delivery_id TEXT NOT NULL,
attempt_no INTEGER NOT NULL CHECK (attempt_no > 0),
provider_ref TEXT,
outcome TEXT NOT NULL,
PRIMARY KEY (tenant_id, delivery_id, attempt_no),
FOREIGN KEY (tenant_id, delivery_id)
REFERENCES delivery (tenant_id, delivery_id)
);
CREATE TABLE preference (
tenant_id TEXT NOT NULL,
recipient_id TEXT NOT NULL,
channel TEXT NOT NULL CHECK (channel IN ('email', 'sms', 'call')),
allowed BOOLEAN NOT NULL,
version INTEGER NOT NULL CHECK (version > 0),
PRIMARY KEY (tenant_id, recipient_id, channel),
FOREIGN KEY (tenant_id, recipient_id)
REFERENCES recipient (tenant_id, recipient_id)
);The tenant is part of both ends of each reference. A t1 delivery cannot reference a recipient that exists only under t2. This preserves data integrity; it does not authenticate the caller. The API must derive or validate tenant scope from the authenticated identity and apply authorization to every operation.
The delivery's unique key prevents a second expansion from creating another logical send for the same tuple. Two workers can both read “nothing exists”; the database still rejects the second conflicting insert. The application handles that conflict by retrieving the existing delivery and comparing the intended payload. A constraint does not deduplicate the external provider call or decide whether two business requests with different payloads are equivalent.
All columns participating in this uniqueness rule are non-null. Otherwise, null treatment can weaken the intended duplicate rule. Likewise, CHECK (attempt_no > 0) and NOT NULL address different cases. Define allowed state transitions separately: a non-null string is not a state machine.
See what a join actually does
To investigate a delivery, join on both parts of the tenant-scoped key:
SELECT d.delivery_id, r.display_name, a.attempt_no, a.outcome
FROM delivery AS d
JOIN recipient AS r
ON r.tenant_id = d.tenant_id AND r.recipient_id = d.recipient_id
LEFT JOIN attempt AS a
ON a.tenant_id = d.tenant_id AND a.delivery_id = d.delivery_id
WHERE d.tenant_id = 't1' AND d.delivery_id = 'd91'
ORDER BY a.attempt_no;This produces two rows for Mira: attempt 1 rejected and attempt 2 accepted. The left join also keeps a delivery visible before any attempt exists, with null attempt fields. Joining only on a tenant-local ID can accidentally mix customers. Joining all deliveries and all attempts for a campaign can also multiply rows and inflate counts: count logical deliveries separately from provider attempts.
Relational joins are useful, but query cost still depends on cardinality, indexes, selected columns and the execution plan. Fetch the required fields and a bounded page rather than loading an entire audience or large JSON payload into an API process. Database latency and application memory are different bottlenecks.
4. Connect each API to a query and an index
An index stores an additional lookup order. It spends space and write work to reduce the records examined for a query. Name the query before naming its index.
| API or operation | Equality/range/order | Supporting key or index |
|---|---|---|
| Get one delivery | tenant + delivery ID | delivery primary key |
| List provider attempts | tenant + delivery ID, attempt order | attempt primary key |
| Open recipient inbox | tenant + recipient, newest timestamp then ID | (tenant_id, recipient_id, created_at DESC, delivery_id DESC) |
| Read current SMS preference | tenant + recipient + channel | preference primary key |
| Investigate a notice's deliveries | tenant + notice, ordered page | Separate notice-oriented index if this query matters |
CREATE INDEX delivery_inbox
ON delivery (tenant_id, recipient_id, created_at DESC, delivery_id DESC);
SELECT delivery_id, notice_id, channel, state, created_at
FROM delivery
WHERE tenant_id = 't1' AND recipient_id = 'r7'
ORDER BY created_at DESC, delivery_id DESC
LIMIT 20;The leading equality columns narrow the search to one tenant's recipient, then the index's order supports the page. An index only on created_at is a different access path: it mixes recipients before filtering. It is not a substitute for this query-specific order. The optimizer may choose another plan; verify with representative data rather than promising a fixed runtime.
Read the diagram
The index starts with equality on tenant and recipient; descending created_at and delivery_id order breaks ties. After cursor (09:00,d91), select older or lower-ID rows.
For a subsequent page, carry the last (created_at, delivery_id) as a cursor and use the same descending order:
SELECT delivery_id, notice_id, channel, state, created_at
FROM delivery
WHERE tenant_id = 't1' AND recipient_id = 'r7'
AND (created_at, delivery_id) < ('2026-10-11 09:00:00+00', 'd91')
ORDER BY created_at DESC, delivery_id DESC
LIMIT 20;The ID breaks timestamp ties. Use immutable ordering fields. A cursor avoids shifting offsets when new items arrive, but it does not freeze a changing dataset; if a consistent export is required, define a snapshot or an upper watermark. Validate cursor tenant/recipient scope and bound page size.
PostgreSQL supplies indexes for primary and unique keys. It does not automatically supply an index on every referencing foreign-key column. Add those required for important joins, deletes or parent lookups; do not create an index for every field. Every additional index increases insert/update cost and maintenance work.
5. Evaluate other storage models against the same questions
Document model: choose the aggregate boundary
A document groups related fields into a nested value. For a notice, a bounded, immutable template snapshot may be a sensible embedded value:
{
"tenantId": "t1",
"noticeId": "n40",
"templateSnapshot": {"version": 8, "locale": "en", "body": "Attendance reminder"},
"selectedAt": "2026-10-11T09:00:00Z"
}The snapshot is small, read with the notice and intentionally historical. Deliveries remain separate documents with tenant, notice and recipient references. Embedding all recipients and all attempts would make the notice grow indefinitely and concentrate unrelated writers on one aggregate.
Read the diagram
Embed the bounded value that shares a lifetime; reference the collection that needs its own paging and updates.
A document store can support field-level updates; changing a field does not inherently require the application to rewrite the whole document. The real questions are atomicity boundaries, growing arrays, indexing, document limits and contention. Flexible structure also does not remove the need for validation, versioning or migration.
Choose this model when aggregate-oriented reads and flexible nested attributes fit the product. Check what happens when two workers update independent deliveries. If separate documents are involved, explicitly choose the store's transaction facility or a recovery protocol; do not assume embedding and referencing provide identical guarantees.
Key-value model: define the key and its authority
A key-value record answers “what value belongs to this exact key?” A cache entry might be inbox:t1:r7:page1, containing a precomputed first page and its build time. The authoritative preference might have a separate key derived from tenant, recipient and channel. Values can be structured, but every required lookup still needs a designed key or an additional access mechanism.
Read the diagram
Cache the display page; read the authoritative preference for the send decision. The cached inbox is not permission to dispatch.
On a miss, load the bounded page from the source and cache it with a chosen expiry. On a hit, tolerate the declared display freshness. A cache outage should degrade to a bounded source read, with protection against many simultaneous misses. Choose invalidation or versioning for updates, and include the tenant in keys to avoid collisions and leakage.
Do not treat every key-value service as an ephemeral cache. A durable service such as DynamoDB can be the source of truth with conditional writes, transactions, a partition/sort-key model and secondary indexes. Its guarantee depends on the operation: global secondary index reads are eventually consistent, so a lagging index should not decide a uniqueness or consent invariant. Redis can also expose richer data types; the label “key-value” alone does not determine durability or query features.
Wide-column model: partition for a specific query
For an inbox, a Cassandra-style table could use partition key (tenant_id, recipient_id, month_bucket) and clustering columns (created_at, delivery_id) ordered descending. The partition key chooses a logical grouping; clustering defines row order within it. This is a query-oriented table, not a universal replacement for the relational schema.
This CQL sketch makes the two roles explicit. Run it in an appropriate Cassandra keyspace when experimenting; the lesson's executable SQL checks do not validate this separate database.
CREATE TABLE inbox_by_recipient_month (
tenant_id TEXT,
recipient_id TEXT,
month_bucket TEXT,
created_at TIMESTAMP,
delivery_id TEXT,
state TEXT,
PRIMARY KEY ((tenant_id, recipient_id, month_bucket), created_at, delivery_id)
) WITH CLUSTERING ORDER BY (created_at DESC, delivery_id DESC);
SELECT created_at, delivery_id, state
FROM inbox_by_recipient_month
WHERE tenant_id = 't1' AND recipient_id = 'r7' AND month_bucket = '2026-10'
LIMIT 20;Read the diagram
In a Cassandra-style inbox table, tenant, recipient and month form the partition key; time and ID cluster ordered rows within it. Crossing months requires another partition read.
A current-month query can retrieve an ordered range without a join. Listing by notice is a different query and may require another table such as deliveries_by_notice, maintained as a projection. Now explain duplicate updates, missing writes, repair and which representation is authoritative.
Time buckets limit growth but do not automatically spread a single hot recipient's current writes. More sub-buckets spread writes at the cost of read fanout. A wide-column store is also not the same thing as an analytical columnar warehouse; aggregation capabilities depend on the chosen system and supporting pipeline.
Graph model: prove the traversal is the main operation
A graph represents nodes and typed edges. Suppose the notification product evolves to answer “which guardians can access students reached through these household and school relationships?” A variable-depth traversal may be a better graph candidate than a fixed delivery lookup.
Read the diagram
The model exposes relationship traversal. The graph describes access candidates; authorization still requires the current product policy.
For a simple fixed relationship, SQL can use a membership table with (tenant_id, recipient_id, student_id, role) and suitable indexes. Choose a graph store only when repeated traversal depth, flexibility and measured workload justify another operational boundary. Limit depth and result size, prevent cycles from causing unbounded work, and enforce tenant and permission filters throughout the traversal.
Make the choice explicit
| Model | Good fit in this example | Cost or limitation to explain |
|---|---|---|
| Relational | Delivery truth, references and transactional constraints | Query/index design, write contention and operational scaling |
| Document | Bounded template or profile aggregate | Growth bounds and multi-document coordination |
| Key-value | Exact-key lookup or replaceable inbox cache | Alternate lookup design and chosen consistency/durability |
| Wide-column | Large ordered recipient history with known queries | Denormalized tables, bucket sizing and repair |
| Graph | Repeated multi-hop membership traversal | Traversal bounds, policy checks and extra operational complexity |
For the original requirements, keep the relational baseline and add a cache only if an observed read bottleneck and freshness contract justify it. A storage label is not a guarantee of speed or correctness.
6. Normalize truth; duplicate deliberately
Normalization separates facts according to what they depend on. In our model, Mira's current display name belongs to the recipient, while a delivery's channel and state belong to the delivery. Storing the current name in every delivery creates multiple values to update when the name changes.
Suppose Mira changes her display name to “Mira K.” A normalized read joins the updated recipient record. A copied inbox page can still display “Mira” until it is invalidated or rebuilt. That may be acceptable for a display page, but only after naming its freshness policy.
Read the diagram
Recipient r7 changes from Mira to Mira K. The source updates once. A cached inbox page retains the old label until invalidation or rebuild; an immutable template snapshot remains historical.
Denormalization can make reads cheaper by precomputing joins or counts. Record the source fields, update event, deduplication identity, freshness target and rebuild method. “We will update both” leaves a failure between the two writes unexplained. Commit the authoritative change and its outbox event together; let a projection consumer apply idempotent changes and expose its lag.
Not every repeated value is a stale copy. A template snapshot, price paid or consent decision recorded at a particular time is a historical fact with its own meaning. Preserve that snapshot when the live value changes. Use names such as template_snapshot or preference_version_checked so an interviewer can see the distinction.
Avoid incrementing dashboard totals blindly on duplicate callbacks. A replayed “delivered” event must not count the same delivery twice. Use a versioned projection or reconcile totals against authoritative logical delivery states, and retain enough history to rebuild within the chosen retention window.
7. Scale the access path before distributing the truth
First measure the bottleneck: examined rows, bytes returned, write rate, locks, storage growth, connection pressure and tail latency. An index can reduce scan work; selecting fewer columns can reduce memory and transfer; a cache or replica can serve eligible reads. A replica may lag, so correctness decisions must use an appropriate authority.
If one database no longer meets the workload after those improvements, choose a shard key that preserves an important locality. Routing by tenant and recipient keeps that recipient's inbox together. Routing by tenant alone keeps customer data together but concentrates a very large tenant. Routing all current writes by date alone creates a hot current bucket.
Read the diagram
Illustrative placement: recipient r7 is assigned to shard A and r8 to shard B. Their inboxes are local. Notice n40 spans both, so its report must aggregate multiple shard results.
The diagram uses an illustrative placement, not a specific vendor's hash function. Choose a stable routing directory or a documented partition scheme; changing shard count is a data-migration problem, not merely editing a modulo expression. A bucket directory can move groups of recipients while limiting how much is relocated at once.
Sharding also changes the constraint story. Our foreign keys and unique constraint work inside one PostgreSQL database. If notices live separately from recipient-sharded deliveries, a local foreign key cannot validate that remote parent. Keep a home authority for notice creation and a defined expansion protocol. Preserve the delivery tuple's uniqueness on the shard that deterministically owns it. Route corrections and retries to the same owner.
Campaign-wide counts now need fanout or an asynchronous aggregate. Decide what happens when one shard is unavailable: return an explicitly partial report, retry, or use a lagging projection under its freshness contract. Do not present a partial count as a final bill or a dispatch authorization.
8. Walk through state changes and failure boundaries
Audience snapshot versus live consent
At 09:00, recipient r8 is selected while SMS preference version 4 is allowed. At 09:01, Omar opts out, creating version 5 with allowed=false. Delivery d92 is still queued. The selected audience remains a historical fact, but the dispatcher checks the current authoritative preference and suppresses this queued delivery.
Read the diagram
The snapshot records selection; version 5 governs the queued delivery's eligibility when dispatch checks it.
There is still a race between checking consent and calling an external provider. Define the product's effective cutoff: for example, suppress when the opt-out commits before dispatch eligibility is claimed. Coordinate preference updates and the dispatch claim at a shared authority if that ordering is required. Persist the checked version and claim time. Once the provider accepts a send, cancellation may no longer be possible; a database transaction cannot roll back that external effect. The diagram demonstrates the queued case, not a universal cancellation guarantee.
Unknown provider result and late callbacks
If the provider call times out, retain the attempt and its correlation reference as unknown. A later callback can resolve that attempt. Deduplicate callbacks and validate transitions so a late “accepted” callback does not erase a confirmed delivery or confuse another attempt. Decide delivery state from the relevant evidence and policy; overwriting the latest status alone loses the explanation.
Deletion and retention
Choose how parent deletion affects history. The example foreign keys reject deleting a referenced parent unless a different deletion policy is explicitly added. That is a deliberate safety boundary, not a full retention solution. Anonymizing a display name can preserve permitted audit relationships, while legal/product rules may require deeper erasure. Delete or invalidate cached and projected personal data too, and prevent replay from resurrecting it.
Bound attempt history, snapshots and outbox retention using product requirements. Keep enough evidence for reconciliation and rebuild, then archive or remove it under the declared policy. Record event time separately from receipt time when late callbacks need ordering analysis.
Schema evolution while old writers still run
Suppose we add suppression_reason to delivery. Add it as optional first; readers understand absent values. Deploy writers that populate it when suppressing, backfill eligible historical rows in restartable batches, and verify counts and sampled values. Only then enforce any stronger condition that the product actually requires. Do not make all delivery rows require a suppression reason: delivered rows have none.
Read the diagram
Add optional suppression_reason before deploying readers and writers; backfill in bounded batches and verify before enforcing a condition only on rows that require it.
Throttle backfills against live traffic, persist progress and plan rollback before dropping the old representation. A new required field, a changed sort key and a moved shard are different migrations; each needs a compatibility and cutover plan.
9. Present a defensible interview answer
“I will store notices, recipients, logical deliveries and provider attempts separately because they have different identities and update lifetimes. The delivery tuple is unique at the authoritative write boundary. Tenant-scoped references prevent cross-customer links, while the API enforces authorization. The inbox uses a recipient/time/ID index and keyset pages. I will keep live consent separate from the selected audience, and treat provider timeouts as unknown attempts. I will add a rebuildable inbox projection only when the measured read workload justifies it.”
An interviewer can now change one requirement and see which part of the model changes. If campaign-wide queries become dominant, add the relevant access path or projection. If a recipient's history becomes huge, examine retention and bucket design. If repeated multi-hop relationships dominate, revisit the graph option. If two workers race, point to the constraint and the external-effect protocol rather than saying only “ACID.”
Check your understanding
Two workers expand the same notice
Both workers read no delivery for t1/n40/r7/sms. How do you keep one logical delivery, and what does that still not guarantee?
Show answer and explanation
Answer: The non-null unique tuple rejects the conflicting second insert. Retrieve the existing delivery and compare request meaning. This protects stored intent, not exactly-once provider delivery; dispatch still needs ownership, provider idempotency where available and reconciliation.
One timestamp appears on two inbox rows
Why is a cursor containing only created_at insufficient?
Show answer and explanation
Answer: It cannot distinguish rows tied at that time. Use (created_at, delivery_id) with the same order and comparison as the index. The immutable tie-breaker makes the page boundary deterministic, although it does not freeze concurrent changes.
A product manager asks to embed every attempt
What would you ask before agreeing?
Show answer and explanation
Answer: Ask for a bound on count/bytes, update contention, retention and query needs. A small immutable snapshot may fit an aggregate; a growing independently updated attempt collection should remain separately addressable and pageable.
The cached inbox says SMS is allowed
Can the dispatcher rely on that page?
Show answer and explanation
Answer: No. It is a display projection with a freshness budget. Check the authoritative preference under the defined claim/cutoff policy and record the version used. Explain the external-provider race rather than promising cancellation after acceptance.
One shard fails during a campaign report
Can you return the sum from the remaining shards?
Show answer and explanation
Answer: Only if the API labels it partial under an explicit contract. A final count requires recovery or a reconciled aggregate. A read-friendly partition does not make cross-partition transactions or reports automatically correct.
One store must answer two different history queries
A wide-column inbox table is keyed by tenant, recipient and month. Will it also efficiently answer “all deliveries for notice n40”?
Show answer and explanation
Answer: Not from that key alone: the recipients may occupy many partitions. Design a notice-oriented access table or a bounded aggregation path, and explain update/rebuild consistency. Choosing a write-friendly store does not remove the need to model each query.
A diagram contains relationships, so should you choose a graph database?
The requirement is a fixed lookup from a guardian to that guardian's students. What evidence would justify a graph store instead of a relational membership table?
Show answer and explanation
Answer: A fixed indexed lookup is a reasonable relational baseline. Repeated variable-depth relationship traversal with a demonstrated workload may justify a graph store. Explain traversal bounds, authorization and the added operational boundary; the presence of arrows alone is not that evidence.
Practice and review
Model a marketplace order with a customer, order items, payment intents and payment attempts. Show sample rows, one business uniqueness constraint, a customer-history query/index and an immutable price snapshot. Explain a payment timeout and a customer-name change. Then challenge your model with a much larger customer and a shard migration.
Score each deliverable 0 if absent, 1 if named, and 2 if the operation and failure behavior are explained. Draw the authoritative record and the derived copy distinctly. Rework the lowest-scoring boundary before adding another technology.
Continue the connection
Database Indexing explains access structures in more detail. Sharding develops locality and movement. Multi-step Processes explains durable workflows, outbox and recovery. Apply those mechanisms to the same schema instead of starting with unrelated boxes.
Primary documentation
- PostgreSQL constraints: primary, foreign, unique, null and check behavior.
- PostgreSQL multicolumn indexes and row comparisons: the inbox access path and cursor comparison.
- MongoDB embedding and unbounded arrays: aggregate and growth decisions.
- DynamoDB Query: partition/sort-key queries and secondary-index consistency.
- Cassandra data modeling: partition and clustering roles.
- Neo4j graph concepts: nodes, typed relationships and properties.