Restaurants and menus with MySQL
9 modules · 15 lessons · 11 exercises · 26 available now
Week 2 overview
- 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
- 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
- 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
- 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
- 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
- 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
- Module 7 Restaurant list test suite
- 2.18 HTTP integration tests with MySQL fixturesIntegration test, Test isolation
- 2.19 Restaurant list integration suite
- Module 8 Restaurant API capacity
- 2.20 Workload-based capacity estimationConnection pool sizing, Storage estimation, InnoDB buffer pool
- 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(default1m). - A black-box integration suite in
backend/integrationthat tests the running API over HTTP with fixtures in MySQL. The grader runs your suite against seven broken implementations.
System architecture and changes


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
Module 1: Database schema and migrations
3 itemsDesign the restaurant and menu tables, understand how InnoDB stores and indexes them, and apply them with versioned migrations.
2.1MySQL tables, keys and InnoDB indexes
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-migrate
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 migrations
Create migration 0001 with the six tables, their keys and the two indexes, then apply and roll it back.
Open exercise →
Module 2: SQL queries and data access
4 itemsTalk to MySQL from Go through database/sql, then let sqlc generate typed functions from the SQL you write.
2.4database/sql: pools, contexts and timeouts
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 generated
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 queries
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 menu
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 →
Module 3: Listing API and pagination
3 itemsServe the restaurant list over HTTP as JSON, paged with a cursor that stays fast at any depth.
2.8JSON HTTP handlers in Go
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) pagination
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 cursor
Build the cursor package and the first real endpoint: nearby restaurants, validated input, keyset pages and an opaque next_cursor.
Open exercise →
Module 4: Response construction
2 itemsLoad a whole menu in a fixed number of queries instead of one per item.
2.11N+1 queries and how to batch them
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 queries
Load a whole menu in at most five batched queries and assemble the nested JSON in Go.
Open exercise →
Module 5: Menu pricing endpoint
2 itemsYou build a menu pricing endpoint that returns a quote and selection feedback for configured restaurant items.
2.13Error classification in Go
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 item
You build
Open exercise →POST /v1/menu/priceto 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.
Module 6: Open-hours index
3 itemsYou 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 hours
Map restaurant IDs to bit positions and minutes to sets of open restaurants, so
Open lesson →GET /v1/restaurantscan calculateis_openfrom memory.2.16Background refresh with atomic.Pointer
Use a context-owned ticker to rebuild the index, then publish each immutable snapshot with
Open lesson →atomic.Pointerso list requests can read it without a data race.2.17GET /v1/restaurants: open status
You build
Open exercise →is_openintoGET /v1/restaurantsand accept an optional RFC 3339attimestamp to evaluate each restaurant's hours. A background refresh keeps the index current onHOURS_REFRESH_INTERVAL.
Module 7: Restaurant list test suite
2 itemsYou 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 fixtures
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 suite
You build a Go integration suite for
Open exercise →GET /v1/restaurantsthat readsTEST_API_URLandTEST_MYSQL_DSN, inserts fixtures and checks HTTP responses. The suite must pass against another correct implementation and detect all seven supplied regressions.
Module 8: Restaurant API capacity
1 itemsYou build a capacity model for the restaurant API that translates browsing activity into request, database and storage demand.
2.20Workload-based capacity estimation
You turn browsing assumptions into request and database load estimates, then compare connection and storage demands with available resources.
Open lesson →
Module 9: Restaurant list extensions
6 itemsYou add optional restaurant-list extensions for cursor integrity, name search and distance-based ordering.
2.21HMAC signing for cursors
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 cursors
You build signed
Open exercise →next_cursorvalues forGET /v1/restaurants, authenticating each pagination position before decoding it. Modified, truncated and extended cursors return400 invalid_cursor.2.23MySQL FULLTEXT search
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 name
You add a
Open exercise →qparameter toGET /v1/restaurantsthat finds restaurants by whole words or word prefixes in their names. Every searchable word must match, while geographic filtering and pagination remain intact.2.25Haversine distance and geo indexes
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 distance
You add
Open exercise →sort=distancetoGET /v1/restaurants, returning active restaurants inside the requested circle, nearest first, with each restaurant's distance in metres.
Completion checklist
What should be true at the end of the week.
- Run
cd backend && make test W=W2and confirm the Week 2 tests pass. - Run
cd backend && make lintand confirm there are no lint findings. - Page through the restaurant list with
limit=2and 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_INTERVALto a short duration and confirmis_openreflects 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
limitto the range1through50; 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/integrationthat send HTTP requests to the running API and use fixtures in MySQL.