Lesson 05

API and Data Before Boxes

Method

Before any box is drawn, the design has a contract and a shape of data. The API says what the system promises, in a few calls. The entities say what it stores and how big each record is. And the way each call reads that data, its access pattern, decides which kind of store fits.

Drawn in that order, the store is chosen for a reason. Drawn the other way, the store is a habit, and the interviewer asks why. This lesson finishes the practice question's Scope with its calls, its entities and its patterns, then names the store they point to, which in a round opens First Design.

The API as the Contract

Write two to five calls, each with its caller, what goes in and what comes out, and mark which call is hot. The read-write ratio agreed in Scope says which one that is.

The practice question needs three. Posting a comment takes the article and the text, with the author taken from the signed-in user, and returns the new comment's ID. Listing an article's comments returns them newest first, a page at a time. Deleting a comment takes the article's ID and the comment's ID. The list call is the hot one: every one of the thirty reads a comment gets comes through it.

The three calls
POST   /articles/{article_id}/comments           {"text": "..."}
       201 {"comment_id": "c_81f3k"}

GET    /articles/{article_id}/comments?limit=20&after=<cursor>
       200 {"comments": [...], "next": "<cursor>"}

DELETE /articles/{article_id}/comments/{comment_id}
       204

The list call takes a cursor, not a page number. The cursor is the time and the ID of the last comment shown, and the next page starts just after it. An offset breaks on a list that grows while it is read. If twenty new comments arrive between page one and page two, page two by offset starts twenty places too early and repeats the twenty the reader just saw. A cursor stays where the reader left off. The news feed problem in Chapter 17 meets the same choice at a larger scale.

Entities and Their Sizes

The entities are the nouns, each with its identifier and a size per record. The size is the number the last lesson multiplied: about a kilobyte per comment, most of it text, the rest its IDs and its time.

Name what this system owns and what it only references. Comments are owned here: their ID, the article's ID, the author's ID, the text and the time posted. Articles and users belong to other systems, and only their IDs are stored. That boundary keeps the design from growing a user table it does not need, and it tells the interviewer where this service's responsibility ends.

Access Patterns

Write each call as a pattern. Six cover nearly everything an interview asks: a lookup by one key, a range within a key, a lookup by a secondary attribute, a search by text, a search by location, and an aggregate over time.

The practice question has one hot pattern and two rare ones. The hot one is an article's comments as a range by time, newest first. The rare ones are a delete of one comment, found by its article and its ID, and a moderator's view of every comment one user has written. The hot pattern is the one that later chooses the partition key, which is the last lesson of Chapter 3.

The order the store is chosen in
APIthe calls
→
Entitiesthe nouns and their sizes
→
Access patternshow each call reads
→
Storechosen by the hot pattern

The Store Follows the Pattern

Seven kinds of store cover what an interview needs. Each makes one kind of access cheap, and each has a known cost. The products named are examples of the kind, not the design.

  • Relational: joins, secondary indexes and transactions across rows are cheap. Spreading it over many machines takes planning, and a query that crosses partitions is expensive. PostgreSQL is one example.
  • Key-value: one lookup by key is cheap, and keys spread over partitions with no planning. Access by anything other than the key needs a second structure kept in step with the first. Amazon DynamoDB is one example.
  • Wide-column: a range of rows within one partition key, kept sorted, is cheap. A query that does not start from the partition key is slow, or refused. Apache Cassandra is one example.
  • Document: a whole record of varying shape, read by its key, is cheap. Joins across documents are the cost. MongoDB is one example.
  • Search index: matching text and ranking the matches is cheap. It is a copy fed from the source of truth, and the copy lags. Elasticsearch is one example.
  • Object store: large blobs written once and read whole are cheap, at almost any size. Changing part of an object means writing all of it again. Amazon S3 is one example.
  • Time series: points appended by time and read back as ranges and rollups are cheap. Changing old points is not what it is built for. Prometheus is one example.
Choosing the store by access pattern
Lookup by one key→Key-value
Joins or multi-row transactions→Relational
A sorted range within one key→Wide-column
Whole records of varying shape→Document
Text search→Search index
Large blobs read whole→Object store
Points over time→Time series
Relational vs Key-Value

A relational store keeps rows with secondary indexes and changes several rows in one transaction. Use it when queries cross entities or a write must change more than one row atomically.

A key-value store answers one lookup by key and spreads keys over partitions without planning. Use it when every hot access is by one key and nothing needs a join.

One Store Until Two Patterns Fight

Start with one store, and add a second only when a pattern the first cannot serve cheaply is a requirement. The common case is text search beside a relational store. The search index is fed asynchronously from the source of truth (Chapter 6, lesson 1), and its cost is a copy that lags and a pipeline that has to keep running.

The practice question's choice comes with its condition, its cost and its trigger. A relational table indexed by article and time serves every call while the data fits one machine. The last lesson put the data at about 66 terabytes with copies, so it is partitioned by article from the start. A relational table split by article would work, at the cost of planning the split. A wide-column store keyed by article and sorted by time does the split itself and fits the hot pattern exactly: one article's comments sit together, in the order they are read. Nothing here needs a join or a transaction across rows, which is what the relational table would have offered.

What it costs is the moderator's view. All the comments by one user cross every article, so that query needs its own table keyed by user, or a global index (Chapter 3, lesson 2). What would change the choice is a requirement that crosses articles and is read as often as the articles are, such as a user's comment history on their profile. You might say: "I'll key comments by article, sorted by time, and give the moderators' by-user view its own table. If profiles start showing comment history, that's when I'd revisit the key."

Misconceptions
  • "The store is chosen by scale." It is chosen by the access pattern first. Scale decides how many partitions, and the pattern decides which kind of store and which key.
  • "Relational stores do not scale." A relational table partitioned by a key that matches the access pattern scales out. What gets expensive is the query that crosses partitions.
  • "A design should use the right store for every entity." Every extra store is a copy to keep in sync, a system to run and a failure to plan for. A second store needs a pattern that the first cannot serve.
  • "The API is a detail for later." The calls are where the hot path and the access patterns come from. A store picked before them has no reason the interviewer can check.
  • "Page numbers are fine for lists." On a list that grows while it is read, an offset repeats or skips items, and a cursor does not.
Why It Matters
  • Write the API in two to five calls, and mark the hot one before drawing.
  • List each call's access pattern next to it, and choose the store from the hot one.
  • Give each entity a size per record, and carry it into the storage estimate.
  • Add a second store only for a named pattern the first cannot serve, and say what keeping it in sync costs.
RelatedURL Shortener: Scope one entity, one patternRange, Hash and Directory secondary indexes, local and globalPicking the Partition Key Chapter 3Queues, Logs and Pub-Sub how a second store is fed

Knowledge Check

Every hot read fetches a range of rows under one key, newest first. Which kind of store fits?

  • A key-value store, holding the whole range as one value per key
  • A search index, ranking the rows under each key by their time
  • A wide-column store keyed by that key, with rows sorted by time
  • An object store, with one object per key rewritten on each change

Why does the list call take a cursor instead of a page number?

  • New comments shift the offsets, so pages repeat; a cursor stays put
  • A cursor lets the client jump straight to any page it wants to see
  • A cursor is shorter to send than a page number and a page size
  • Page numbers only work when the list is sorted oldest first

You add a search index beside the main store for text search. What does it cost?

  • Every write must commit to both stores inside one transaction
  • A copy that lags the source, and a pipeline to keep it fed
  • Reads of the main store slow down, since they now pass through it
  • The main store can no longer serve its lookups by key directly

Which access pattern should choose the comments' partition key?

  • The moderator's view of every comment written by one user
  • The delete of one comment, since it must change exactly one row
  • The hot one, an article's comments read as a range by time
  • Whichever pattern the interviewer seems most likely to probe

Why is the store chosen after the API and the access patterns, not before?

  • Store products change often, so the choice is left as late as possible
  • The interviewer scores the API first and the store only if time remains
  • Scale decides the store, and the scale is known only after the API
  • The patterns decide the store's kind; picked earlier, it has no reason

You got correct