From User Actions to APIs & Database Schemas
Translate three user actions into clean REST endpoints, status codes, relational or NoSQL tables, keys, and the indexes that avoid full scans.
In this lesson (4 bite-sized sections)
Turn user actions into a REST contract
In many intern interviews, candidates jump straight to boxes labeled "Backend" and "Database" without ever showing how a user click turns into an HTTP request and a stored record. Bridging actions to APIs and tables takes only five minutes and makes the rest of your architecture almost write itself.
Start from 3 to 4 core user actions and turn each verb-noun pair into one REST endpoint with explicit HTTP status codes. Imagine a link-bookmarking app where signed-in users save a bookmark, list their saved links, and delete a link:
POST /v1/bookmarkswith JSON body{ url, title }creates a row and returns201 Created(or400/422for a malformed URL,401if unauthenticated).GET /v1/bookmarks?cursor=...&limit=20returns200 OKwith the user's newest links and anext_cursortoken for clean pagination.DELETE /v1/bookmarks/{id}removes the row and returns204 No Content(or404 Not Foundif missing,403 Forbiddenif another user owns that bookmark).
Naming the exact verbs, paths, and failure codes immediately clarifies what data your server must validate and store.
Map endpoints to tables, keys, and database families
Every core noun in your endpoints becomes a table or collection. Default to a relational database
(PostgreSQL) whenever you have structured records, clear ownership, or foreign-key relationships
such as users and bookmarks joined through bookmarks.user_id. Relational engines give you
strong ACID transactions, unique constraints, and flexible queries out of the box.

Reach for a specialized store only when a specific access pattern demands it: a key-value store (Redis, DynamoDB) for single-key lookups and hot caches, a document store for nested variable payloads, object storage (S3) for large binary files like images and PDFs, or a search index for full-text queries. Never shove multi-megabyte files into relational rows when an object store URL column is cheaper and faster.
- iduuid
- emailtext UNIQUE
- created_attimestamptz
- iduuid
- user_iduuid
- urltext
- titletext
- created_attimestamptz
- bookmarksn-1users— owned by
Pick the cleanest primary storage family for each everyday product requirement.
Sort 5 more items to check
Pick the 1 to 2 indexes that prevent full-table scans
Primary keys give you fast lookups by id, yet most product screens do not fetch by bookmark
id. Your list endpoint executes WHERE user_id = $1 ORDER BY created_at DESC LIMIT 20. Without
a secondary index supporting that access pattern, the database scans every row in the table (an
O(N) full-table scan) and stalls as soon as the table hits millions of rows.
One targeted composite B-tree index solves the problem: put the equality filter column first and the
sort column second so the engine jumps directly to that owner's slice in O(log N) time and reads
20 already-ordered rows. Resist indexing every column just in case. Every extra index consumes RAM
and disk and forces extra tree updates on every INSERT or UPDATE.
Cross-check the bridge before drawing boxes
Before moving to architecture diagrams, run a quick 30-second audit on your board:
- Does every endpoint read or write a real table you drew?
- Does every frequent
WHEREandORDER BYquery have an index (or key-value lookup) that avoids scanning the full table? - Are unique business rules (such as one email per account or one RSVP per user per event) enforced by a unique constraint in the schema rather than hoped for in application code?
When all three checks pass, your API, schema, and indexes form a rock-solid foundation for scaling. That short check also catches missing foreign keys, orphan tables, and unindexed list endpoints before you ever draw a cache or load balancer.
Sources: PostgreSQL Multicolumn Indexes · MDN HTTP Response Status Codes · Designing Data-Intensive Applications, ch. 3
from bisect import bisect_left
# Pyodide-safe model of SQL EXPLAIN QUERY PLAN for:
# SELECT id, title FROM posts WHERE author_id = ? ORDER BY created_at DESC LIMIT 10
NUM_ROWS, NUM_AUTHORS, TARGET_AUTHOR, LIMIT = 500, 25, 7, 10
posts = [(i, i % NUM_AUTHORS, 1_700_000_000 + i * 60, f"Post #{i}") for i in range(1, NUM_ROWS + 1)]
def run_no_index():
top = sorted((r for r in posts if r[1] == TARGET_AUTHOR), key=lambda r: r[2], reverse=True)[:LIMIT]
return "SCAN posts (USE TEMP B-TREE FOR ORDER BY)", len(posts), top
def run_created_only():
top, scanned = [], 0
for r in sorted(posts, key=lambda r: -r[2]):
scanned += 1
if r[1] == TARGET_AUTHOR:
top.append(r)
if len(top) == LIMIT:
break
return "SCAN posts USING INDEX idx_posts_created", scanned, top
def run_composite():
# Models: CREATE INDEX idx_posts_author_created ON posts(author_id, created_at DESC)
idx = sorted((r[1], -r[2], r) for r in posts)
pos = bisect_left([(e[0], e[1]) for e in idx], (TARGET_AUTHOR, float("-inf")))
top = [e[2] for e in idx[pos : pos + LIMIT] if e[0] == TARGET_AUTHOR]
return "SEARCH posts USING INDEX idx_posts_author_created", len(top), top
for label, (plan, scanned, top) in [("BEFORE", run_no_index()), ("WRONG ", run_created_only()), ("AFTER ", run_composite())]:
print(f"{label} | {plan} | inspected={scanned:>3}/{NUM_ROWS} | newest={top[0][0] if top else None}")Apply
Your turn
The task this lesson builds to.
Translate three core actions for an event RSVP app (create event, RSVP to event, list an event's attendees) into REST endpoints with status codes, database tables with keys, and the 1 to 2 indexes that keep queries fast.
Think about
- Which HTTP verbs and status codes cleanly express creation, duplicate RSVP conflicts, and missing events?
- What primary keys, foreign keys, and unique constraints enforce one RSVP per user per event?
- Which composite index prevents a full-table scan when listing an event's attendees in order?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Translate a team task-tracker workflow (create task, assign task, list open tasks for a project ordered by due date) into REST endpoints, relational tables, and composite indexes, and justify why one blob or cache store sits outside SQL.
Think about
- How do you structure a partial update like assigning a task (
PATCH) vs creating one (POST)? - What exact column order belongs in the composite index for
WHERE project_id = ? AND status = 'open' ORDER BY due_at ASC? - Which piece of task data (file attachments or hot project summary counts) belongs outside PostgreSQL?
Draft your design answer here Save your draft, compare against the model answer, and track progress.