Sub topic 6
Sketch the API and the data model
This chapter assumes you have already written down functional and non-functional requirements and a rough capacity estimate. It also assumes you can read HTTP requests and short Python snippets, and that you know what a relational table and an index are.
The API and the data model are the first concrete artifacts in a design. They turn a list of requirements into operations and stored records. They also expose the access patterns, meaning the specific queries the system must answer quickly. Those patterns decide which storage and scaling choices make sense later.
Why the API comes first
Boxes on a whiteboard do not say what flows between them. An API sketch does. Each operation you list forces three decisions:
- Who calls it, and with what inputs.
- What it returns, and how large the result can be.
- What the data layer must do to serve it.
The third decision is why you sketch the API before choosing a database. "Fetch one item by ID" and "list a user's items, newest first" need different indexes and may need different partitioning. Choosing storage before you know which of these you need means guessing.
From requirements to operations
Start with the functional requirements and write one operation for each verb. Keep the first pass small. For a generic item service, the requirements might be "users create items, read an item, and see a list of their own items." Annotate each operation with its expected frequency from your capacity estimate.
| Operation | Method and path | Rough load | Data-layer need |
|---|---|---|---|
| Create item | POST /v1/items | about 579 average write QPS | Insert with a unique ID |
| Read item | GET /v1/items/{item_id} | part of about 11,574 read QPS | Point lookup by ID |
| List a user's items | GET /v1/users/{owner_id}/items | part of the same read load | Range scan by owner, newest first |
The load column does real work. The estimate says reads outnumber writes by about 20 to 1, so the two read operations are where most design effort belongs. If you cannot say which operation is hottest, go back to your assumptions before going further.
Designing the API
Here is the sketch from the plan, with an idempotency header added to the create call.
POST /v1/items
Content-Type: application/json
Idempotency-Key: 7d1c9f4e-2b0a-4c57-9a43-1f6f1d0c8b21
{"owner_id": "user:42", "body": "hello"}
GET /v1/items/{item_id}
GET /v1/users/{owner_id}/items?limit=20&cursor=abc123Several choices here are worth stating out loud.
Resources and identifiers
Use nouns for resources (items, users) and let the HTTP method carry the verb. Version the path (/v1/) so you can change the contract later without breaking existing clients.
Decide where IDs come from. Server-generated IDs avoid collisions between clients. Sequential integers are easy to store but leak volume and are hard to generate across several machines. Random UUIDs need no coordination but sort badly in some indexes. Time-ordered IDs sort by creation time and need no coordination. In an interview or design review, name one and give a reason.
Idempotency on writes
A client that times out on a POST cannot tell whether the item was created. If it retries, it may create a duplicate. An idempotency key lets the server recognize a retry. The server stores the key with the result, and a repeated request with the same key returns the stored result instead of writing again. Reads and PUT/DELETE are naturally safe to retry. Plain POST is not. This detail matters again when you plan for failure.
Pagination
Any list operation that can return many rows needs pagination. There are two common forms:
| Style | How it works | Strength | Weakness |
|---|---|---|---|
| Offset (`?offset=1000&limit=20`) | Skip N rows, return the next page | Simple, allows jumping to page N | The database still walks the skipped rows. Rows inserted during paging cause duplicates or gaps. |
| Cursor (`?cursor=abc123`) | Return rows after the last row seen | Constant cost per page, stable under inserts | No random page access |
The sketch uses a cursor because the list is newest-first and new items arrive constantly. The cursor is an opaque string to the client. Internally it holds the sort key of the last row returned. Here is a runnable version of that logic:
import base64
import json
ITEMS = [
{"item_id": f"i{n:03d}", "owner_id": "user:42", "created_at": 1000 + n}
for n in range(1, 8)
]
def encode_cursor(created_at: int, item_id: str) -> str:
raw = json.dumps([created_at, item_id]).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii")
def decode_cursor(cursor: str) -> tuple:
return tuple(json.loads(base64.urlsafe_b64decode(cursor.encode("ascii"))))
def list_items(owner_id: str, limit: int = 3, cursor: str | None = None):
rows = sorted(
(r for r in ITEMS if r["owner_id"] == owner_id),
key=lambda r: (r["created_at"], r["item_id"]),
reverse=True,
)
if cursor:
last = decode_cursor(cursor)
rows = [r for r in rows if (r["created_at"], r["item_id"]) < last]
page = rows[:limit]
next_cursor = None
if len(rows) > limit:
tail = page[-1]
next_cursor = encode_cursor(tail["created_at"], tail["item_id"])
return page, next_cursor
cursor = None
while True:
page, cursor = list_items("user:42", limit=3, cursor=cursor)
print([r["item_id"] for r in page])
if cursor is None:
breakThe sort key is the pair (created_at, item_id). Timestamps alone can tie, and a tie would make the cursor skip or repeat rows. Adding the unique ID makes the order total. A real database does the same with a WHERE (created_at, item_id) < (?, ?) clause backed by an index.
Errors, limits, and authentication
Add a line for each of these, even if only in words:
- Status codes: 201 for create, 404 for a missing item, 400 for bad input, 429 when a client is rate limited.
- A maximum
limit, for example 100, so one request cannot ask for the whole table. - A maximum
bodysize. Your 500-byte record assumption holds only if the API enforces something close to it. - Who may read an item. If the answer is "anyone with the ID," say so, because it affects caching later.
Designing the data model
The data model lists the entities you store, their fields, and how they relate. Derive it from the API, not from the real-world nouns you find in the problem statement.
Start with entities and relationships
For the item service there are two entities. A user owns many items, and each item has one owner.
Let access patterns choose keys and indexes
Write each query next to the key that serves it:
| Query | Needed access path |
|---|---|
| Get item by `item_id` | Primary key on `item_id` |
| List items by `owner_id`, newest first | Secondary index on `(owner_id, created_at DESC, item_id DESC)` |
That second index is the cursor logic from the Python example, expressed as a schema. If a requirement says "search items by text," it needs a different structure, such as a search index, and the data model must say so now. A requirement you cannot map to an access path is a gap in the design.
Estimate row size and growth
Check the model against your capacity numbers. At 500 bytes per record and 25 GB of new data per day, about 9.1 TB per year, the item table outgrows one machine within a couple of years. The model should be ready for that. Keep owner_id in every item row so you can partition on it, and avoid queries that join across owners.
Pick a partition key with the queries in mind
The partition key decides which shard holds a row. The plan's hash-partitioning helper makes this concrete:
import hashlib
def shard_for(key: str, shard_count: int) -> int:
digest = hashlib.md5(key.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big") % shard_count
print(shard_for("user:42", 4))
print(shard_for("user:43", 4))Two options follow from the access patterns:
- Partition by
owner_id. All of a user's items live on one shard, so the list query touches one shard. Point lookups byitem_idneed to know the owner, or need a lookup table from item to owner. One very active user can create a hot shard. - Partition by
item_id. Rows spread evenly, and point lookups go to one shard. The list query must ask every shard and merge the results.
Because the list query is read-heavy in this example, partitioning by owner_id is a reasonable first choice. You would revisit it if a few users generate most of the traffic. Note also that changing shard_count remaps most keys. That cost is part of the data model decision, not only an operations concern.
Common errors
- Designing tables first. The schema then reflects the domain vocabulary, not the queries, and the hottest query ends up needing a full scan.
- Returning unbounded lists. Every collection endpoint needs a page size cap.
- Offset pagination on a fast-moving list, which produces duplicates and gaps.
- Cursors that sort on a non-unique field, which skip or repeat rows at ties.
- Retry-unsafe creates. Without an idempotency key, a network timeout can produce duplicate records.
- Fields with no owner in the API. If the data model needs
owner_idfor partitioning, the API must carry it or derive it from authentication.
Exercise
Your list endpoint is GET /v1/users/{owner_id}/items?limit=20&cursor=... and sorts by created_at descending. Two items for the same user are created in the same second. Why can a cursor based only on created_at return wrong pages, and what is the fix? Also name the index that serves the query.
Show answer
With only created_at in the cursor, the server asks for rows strictly older than the last timestamp. Any other row with the same timestamp that did not fit on the previous page is skipped. If the comparison is "older than or equal," rows already shown are repeated. The fix is to add a unique tiebreaker, item_id, and sort and compare on the pair (created_at, item_id). The index is on (owner_id, created_at DESC, item_id DESC), so the database can read one owner's rows in order without sorting.
Exercise
A teammate proposes partitioning the items table by item_id for even distribution. Using the access patterns in this chapter, give one benefit and one cost of that choice compared with partitioning by owner_id.
Show answer
Benefit: rows spread evenly across shards, so no single heavy user creates a hot shard, and a lookup by item_id goes to exactly one shard. Cost: the list-by-owner query, which is part of the dominant read load, must be sent to every shard and the results merged, which raises latency and load per request. Partitioning by owner_id reverses these trade-offs.