Restaurants and menus with MySQL

9 modules · 15 lessons · 11 exercises · 26 available now

Week 2 overview

  1. Module 1 Database schema and migrations
    • 2.1 MySQL tables, keys and InnoDB indexesInnoDB, Primary key, Foreign key, B+tree, Clustered index, Secondary index, Composite index, Leftmost-prefix rule, EXPLAIN
    • 2.2 Versioned migrations with golang-migrateDatabase migration, golang-migrate
    • 2.3 Write the restaurant and menu migrations
  2. Module 2 SQL queries and data access
    • 2.4 database/sql: pools, contexts and timeoutsdatabase/sql, Connection pool, Query timeout
    • 2.5 sqlc: SQL first, Go generatedsqlc, Dependency injection
    • 2.6 Generate the restaurant and menu queries
    • 2.7 Seed 50 restaurants and one full menu
  3. Module 3 Listing API and pagination
    • 2.8 JSON HTTP handlers in GoJSON struct tags, HTTP status codes
    • 2.9 Keyset (cursor) paginationKeyset pagination, Opaque cursor
    • 2.10 GET /v1/restaurants with a cursor
  4. Module 4 Response construction
    • 2.11 N+1 queries and how to batch themN+1 queries, Batch loading
    • 2.12 GET /v1/restaurants/{id}/menu in five queries
  5. Module 5 Menu pricing endpoint
    • 2.13 Error classification in GoError wrapping, Sentinel error, Typed error
    • 2.14 POST /v1/menu/price: price a configured item
  6. Module 6 Open-hours index
    • 2.15 Bitsets for opening hoursBitset, Half-open interval
    • 2.16 Background refresh with atomic.PointerGoroutine lifecycle, atomic.Pointer
    • 2.17 GET /v1/restaurants: open status
  7. Module 7 Restaurant list test suite
    • 2.18 HTTP integration tests with MySQL fixturesIntegration test, Test isolation
    • 2.19 Restaurant list integration suite
  8. Module 8 Restaurant API capacity
    • 2.20 Workload-based capacity estimationConnection pool sizing, Storage estimation, InnoDB buffer pool
  9. Module 9 Restaurant list extensions
    • 2.21 HMAC signing for cursors (optional)HMAC, Constant-time comparison, Signed cursor
    • 2.22 GET /v1/restaurants: signed cursors (optional)
    • 2.23 MySQL FULLTEXT search (optional)FULLTEXT index, Boolean mode search
    • 2.24 GET /v1/restaurants: search by name (optional)
    • 2.25 Haversine distance and geo indexes (optional)Bounding box, Haversine distance
    • 2.26 GET /v1/restaurants: sort by distance (optional)

Weekly learning objectives

Week 1 gave you a Go server that rate limits requests and nothing else. This week it gets its first real data: restaurants and their menus, stored in MySQL and served as JSON.

By Thursday you will have:

  • A schema for restaurants, items, sizes and configurable options, created by versioned migrations.
  • Typed queries generated by sqlc from SQL you write yourself.
  • GET /v1/restaurants, a restaurant list paged with a cursor that stays fast on page 1,000.
  • GET /v1/restaurants/{id}/menu, a whole menu assembled in at most five SQL statements.
  • POST /v1/menu/price, an endpoint that returns a quote with every selection error for a configured item.
  • An open-hours index that answers whether each restaurant is open, rebuilt in the background every HOURS_REFRESH_INTERVAL (default 1m).
  • A black-box integration suite in backend/integration that tests the running API over HTTP with fixtures in MySQL. The grader runs your suite against seven broken implementations.

System architecture and changes

By Thursday the week 1 router and Redis limiter route restaurant requests to new handlers, which query MySQL through sqlc and check an in-memory open-hours index that is rebuilt from MySQL in the background.By Thursday the week 1 router and Redis limiter route restaurant requests to new handlers, which query MySQL through sqlc and check an in-memory open-hours index that is rebuilt from MySQL in the background.

How to complete the coursework

Each module is a short run of lessons followed by the exercise that uses them. Read the lessons in order; every exercise only needs concepts taught before it. Underlined words link to a concept guide when you need a reminder.

Exercises are written and run in your own editor, inside the zomato-prep repo. The Run locally panel on each exercise lists the commands and what passing looks like. Use the hints before the solution: the struggle is where the learning happens.

Modules

  1. Module 1: Database schema and migrations

    3 items

    Design the restaurant and menu tables, understand how InnoDB stores and indexes them, and apply them with versioned migrations.

    • 2.1MySQL tables, keys and InnoDB indexesLesson · 35 min

      What InnoDB is, column types, primary and foreign keys, how InnoDB stores rows in a clustered B+tree, composite indexes and the leftmost-prefix rule, and reading EXPLAIN.

      Open lesson →
    • 2.2Versioned migrations with golang-migrateLesson · 20 min

      Why schema changes live in numbered files, how golang-migrate tracks what ran, writing up and down files, and what to do when a migration fails halfway.

      Open lesson →
    • 2.3Write the restaurant and menu migrationsExercise · 70 min

      Create migration 0001 with the six tables, their keys and the two indexes, then apply and roll it back.

      Open exercise →
  2. Module 2: SQL queries and data access

    4 items

    Talk to MySQL from Go through database/sql, then let sqlc generate typed functions from the SQL you write.

    • 2.4database/sql: pools, contexts and timeoutsLesson · 30 min

      What *sql.DB really is, opening and sizing the pool, the three query methods, placeholders and NULLs, and putting every query under a 500 ms deadline.

      Open lesson →
    • 2.5sqlc: SQL first, Go generatedLesson · 30 min

      Write SQL, generate typed Go: the sqlc config, query annotations, sqlc.arg and sqlc.slice, the types it picks, WithTx, and wiring handler, service and queries without a framework.

      Open lesson →
    • 2.6Generate the restaurant and menu queriesExercise · 60 min

      Write the restaurant and menu queries in SQL, configure sqlc, and commit the generated internal/db package.

      Open exercise →
    • 2.7Seed 50 restaurants and one full menuExercise · 45 min

      Write an idempotent seed command: 50 restaurants within 5 km of Gurgaon and one Farmhouse pizza menu, the same data on every run.

      Open exercise →
  3. Module 3: Listing API and pagination

    3 items

    Serve the restaurant list over HTTP as JSON, paged with a cursor that stays fast at any depth.

    • 2.8JSON HTTP handlers in GoLesson · 30 min

      The anatomy of a handler, reading query, path and body input, validating at the edge, struct tags and empty slices, choosing status codes, and testing a handler with httptest.

      Open lesson →
    • 2.9Keyset (cursor) paginationLesson · 35 min

      Why OFFSET slows down and shifts pages, continuing from the last row instead, tie-breakers and row comparisons, opaque cursors, the limit+1 trick, and what EXPLAIN should show.

      Open lesson →
    • 2.10GET /v1/restaurants with a cursorExercise · 90 min

      Build the cursor package and the first real endpoint: nearby restaurants, validated input, keyset pages and an opaque next_cursor.

      Open exercise →
  4. Module 4: Response construction

    2 items

    Load a whole menu in a fixed number of queries instead of one per item.

    • 2.11N+1 queries and how to batch themLesson · 25 min

      Why a query per row explodes, loading each level of a nested menu in one batched query, assembling the tree in Go with index maps, and why one giant JOIN is worse.

      Open lesson →
    • 2.12GET /v1/restaurants/{id}/menu in five queriesExercise · 75 min

      Load a whole menu in at most five batched queries and assemble the nested JSON in Go.

      Open exercise →
  5. Module 5: Menu pricing endpoint

    2 items

    You build a menu pricing endpoint that returns a quote and selection feedback for configured restaurant items.

    • 2.13Error classification in GoLesson · 30 min

      You can preserve the cause of a lookup failure while returning invalid selections as quote data, allowing the pricing endpoint to map each outcome correctly.

      Open lesson →
    • 2.14POST /v1/menu/price: price a configured itemExercise · 90 min

      You build POST /v1/menu/price to price an item, size, chosen options and quantity, returning a quote with every selection error. Invalid selections return HTTP 200 with zero prices, while malformed requests and missing items use HTTP errors.

      Open exercise →
  6. Module 6: Open-hours index

    3 items

    You build an in-memory open-hours index that adds an accurate open or closed status to each restaurant in the restaurant list.

    • 2.15Bitsets for opening hoursLesson · 25 min

      Map restaurant IDs to bit positions and minutes to sets of open restaurants, so GET /v1/restaurants can calculate is_open from memory.

      Open lesson →
    • 2.16Background refresh with atomic.PointerLesson · 30 min

      Use a context-owned ticker to rebuild the index, then publish each immutable snapshot with atomic.Pointer so list requests can read it without a data race.

      Open lesson →
    • 2.17GET /v1/restaurants: open statusExercise · 90 min

      You build is_open into GET /v1/restaurants and accept an optional RFC 3339 at timestamp to evaluate each restaurant's hours. A background refresh keeps the index current on HOURS_REFRESH_INTERVAL.

      Open exercise →
  7. Module 7: Restaurant list test suite

    2 items

    You build a Go integration suite that verifies restaurant-list pagination, geographic filtering and cursor errors against a running API and MySQL.

    • 2.18HTTP integration tests with MySQL fixturesLesson · 30 min

      Test a running API with database-backed fixtures so your integration suite can verify pagination and filtering through the actual restaurant-list contract.

      Open lesson →
    • 2.19Restaurant list integration suiteExercise · 60 min

      You build a Go integration suite for GET /v1/restaurants that reads TEST_API_URL and TEST_MYSQL_DSN, inserts fixtures and checks HTTP responses. The suite must pass against another correct implementation and detect all seven supplied regressions.

      Open exercise →
  8. Module 8: Restaurant API capacity

    1 items

    You build a capacity model for the restaurant API that translates browsing activity into request, database and storage demand.

    • 2.20Workload-based capacity estimationLesson · 50 min

      You turn browsing assumptions into request and database load estimates, then compare connection and storage demands with available resources.

      Open lesson →
  9. Module 9: Restaurant list extensions

    6 items

    You add optional restaurant-list extensions for cursor integrity, name search and distance-based ordering.

    • 2.21HMAC signing for cursorsLesson · 25 min · Optional

      You can authenticate a cursor before decoding its keyset position, allowing W2O1 to reject modified pagination requests without changing the restaurant-list contract.

      Open lesson →
    • 2.22GET /v1/restaurants: signed cursorsExercise · 60 min · Optional

      You build signed next_cursor values for GET /v1/restaurants, authenticating each pagination position before decoding it. Modified, truncated and extended cursors return 400 invalid_cursor.

      Open exercise →
    • 2.23MySQL FULLTEXT searchLesson · 25 min · Optional

      You can turn user input into safe boolean-mode prefix terms and query a FULLTEXT index while keeping ID-based pagination valid in W2O2.

      Open lesson →
    • 2.24GET /v1/restaurants: search by nameExercise · 75 min · Optional

      You add a q parameter to GET /v1/restaurants that finds restaurants by whole words or word prefixes in their names. Every searchable word must match, while geographic filtering and pagination remain intact.

      Open exercise →
    • 2.25Haversine distance and geo indexesLesson · 30 min · Optional

      You can narrow nearby restaurant candidates with a bounding box, verify the circle with haversine distance, and keep distance-based pagination deterministic in W2O3.

      Open lesson →
    • 2.26GET /v1/restaurants: sort by distanceExercise · 90 min · Optional

      You add sort=distance to GET /v1/restaurants, returning active restaurants inside the requested circle, nearest first, with each restaurant's distance in metres.

      Open exercise →

Completion checklist

What should be true at the end of the week.

  • Run cd backend && make test W=W2 and confirm the Week 2 tests pass.
  • Run cd backend && make lint and confirm there are no lint findings.
  • Page through the restaurant list with limit=2 and confirm every seeded restaurant appears exactly once.
  • Submit a quote request with multiple invalid selections and confirm HTTP 200 returns every selection error with both price fields set to 0.
  • Set HOURS_REFRESH_INTERVAL to a short duration and confirm is_open reflects changes after the open-hours index refreshes.

Week requirements

Rules every piece of code this week must follow.

  • Make schema changes only through backend/db/migrations; do not create tables elsewhere.
  • Run every database call with a context that has a deadline.
  • Do not execute a database query inside a loop.
  • Assemble each restaurant's menu in at most five SQL statements.
  • Clamp the restaurant-list limit to the range 1 through 50; return HTTP 400 for a bad cursor, not HTTP 500.
  • Return API errors using the structured body {error, message, field}.
  • Write black-box integration tests in backend/integration that send HTTP requests to the running API and use fixtures in MySQL.
Restaurants and menus with MySQLWeek 2 · 26 items available
Start Module 1: Database schema and migrations