Authentication, orders and Kafka events

8 modules · 13 lessons · 11 exercises · 24 available now

Week 3 overview

  1. Module 1 Account authentication
    • 3.1 Password hashing and random secretsbcrypt, crypto/rand
    • 3.2 JWT and refresh token rotationJWT, Access token, Refresh token, Refresh token rotation
    • 3.3 POST /v1/auth/*: signup, login and refresh
    • 3.4 Bearer middleware and request contextContext values
    • 3.5 GET /v1/me: caller account
  2. Module 2 Order creation
    • 3.6 Migration 0006: order tables
    • 3.7 Transactions in Go and MySQLTransaction, Duplicate-key error (1062)
    • 3.8 Isolation levels and anomaliesIsolation level, Consistent read, Next-key lock, Write skew
    • 3.9 Idempotency keysIdempotency key, SET NX
    • 3.10 POST /v1/orders: idempotent checkout
  3. Module 3 Order lifecycle API
    • 3.11 State machines and optimistic lockingState machine, Optimistic locking
    • 3.12 POST /v1/orders/{id}/events: order lifecycle
  4. Module 4 Kafka event publishing
    • 3.13 Kafka partitions and groupsPartition, Consumer group, At-least-once delivery
    • 3.14 Transactional outbox writesDual-write problem, Transactional outbox
    • 3.15 Outbox relay to order-events
  5. Module 5 Reliable event consumers
    • 3.16 Idempotency and retry handlingIdempotent consumer, Dead-letter queue
    • 3.17 Notifier worker with retries and DLQ
  6. Module 6 API and worker shutdown
    • 3.18 Signal-driven shutdownGraceful shutdown, OS signal
    • 3.19 API and notifier shutdown
  7. Module 7 Order service capacity
    • 3.20 Capacity estimationWrite throughput, Consumer lag
  8. Module 8 Account and outbox extensions
    • 3.21 Refresh families, relay locking, login throttling (optional)Refresh token family, Refresh token reuse detection, SELECT FOR UPDATE, SKIP LOCKED, Credential stuffing
    • 3.22 POST /v1/auth/refresh: detect token reuse (optional)
    • 3.23 Concurrent outbox relay (optional)
    • 3.24 POST /v1/auth/login: rate limit attempts (optional)

Weekly learning objectives

Week 2 gave you restaurants and menus served from MySQL. This week you add accounts and orders, then send every order change through Kafka to a background notifier without losing or duplicating its effect.

By the end of the week you will have:

  • Account authentication: POST /v1/auth/signup, POST /v1/auth/login and POST /v1/auth/refresh, issuing 15-minute access tokens and rotating refresh tokens.
  • A protected account endpoint: GET /v1/me, which reads the caller from the bearer token.
  • Order creation: POST /v1/orders, which prices orders on the server and uses an idempotency key to make checkout retries safe.
  • An order lifecycle API: POST /v1/orders/{id}/events, GET /v1/orders and GET /v1/orders/{id}, with role-based transitions and order history.
  • Kafka event publishing: an outbox relay that publishes order changes to Redpanda, keyed by order id.
  • Reliable event consumers: a notifier in cmd/worker that records one notification per event, retries failures and sends exhausted or unreadable records to the dead-letter topic.
  • API and worker shutdown: graceful SIGTERM handling in both binaries.

System architecture and changes

Requests pass a JWT middleware; handlers write an order, its event and an outbox row to MySQL in one transaction and keep refresh tokens and idempotency keys in Redis; a relay polls the outbox into Redpanda, and a notifier worker consumes it and writes deduplicated notifications back to MySQL.Requests pass a JWT middleware; handlers write an order, its event and an outbox row to MySQL in one transaction and keep refresh tokens and idempotency keys in Redis; a relay polls the outbox into Redpanda, and a notifier worker consumes it and writes deduplicated notifications back to MySQL.

Key concepts and principles

Three guarantees show up again and again, and the week is about keeping them apart:

  • Atomic writes: a MySQL transaction makes the order, its event and its outbox row appear together or not at all.
  • At-least-once delivery: the relay and Kafka can deliver the same event more than once, for example after a crash between publishing and marking it sent.
  • Idempotent processing: an idempotency key on the way in and a dedupe table on the way out turn repeated delivery into exactly one effect.

How to complete the coursework

Each module is a short run of lessons followed by the exercise that uses them. Work through the modules in order because each exercise builds on the components from the previous ones.

Run make up before you start: MySQL, Redis and Redpanda all run in Docker. Exercises are written in your own editor inside the zomato-prep repo, and the Run locally panel lists the commands and what passing looks like.

Modules

  1. Module 1: Account authentication

    5 items

    You build account registration and token issuance so customers, restaurants and riders can authenticate API requests.

    • 3.1Password hashing and random secretsLesson · 25 min

      You can hash passwords without storing plaintext and generate opaque refresh-token values for the authentication endpoints.

      Open lesson →
    • 3.2JWT and refresh token rotationLesson · 35 min

      You can issue a verifiable 15-minute access token and rotate a one-use refresh token, which signup, login and refresh need to return credentials safely.

      Open lesson →
    • 3.3POST /v1/auth/*: signup, login and refreshExercise · 110 min

      You build POST /v1/auth/* to register accounts, exchange passwords for token pairs, and rotate refresh tokens. Each refresh token works once.

      Open exercise →
    • 3.4Bearer middleware and request contextLesson · 25 min

      You can verify a bearer token once and pass the authenticated caller through the request context so GET /v1/me can retrieve the correct account.

      Open lesson →
    • 3.5GET /v1/me: caller accountExercise · 50 min

      You build GET /v1/me to return the authenticated caller's account details using a verified bearer token. Invalid credentials return the same 401 unauthorized response.

      Open exercise →
  2. Module 2: Order creation

    5 items

    You build transactional order creation with idempotency so checkout can safely retry without creating duplicate orders.

    • 3.6Migration 0006: order tablesExercise · 50 min

      You add migration 0006 with the orders, order_lines, order_events and outbox tables used to store orders and their events. The schema enforces global event ID uniqueness, order references, required defaults and indexed query paths.

      Open exercise →
    • 3.7Transactions in Go and MySQLLesson · 30 min

      Use a database/sql transaction to commit an order and its dependent records together, so W3B4 never returns a partially written order.

      Open lesson →
    • 3.8Isolation levels and anomaliesLesson · 35 min

      You can choose transaction isolation levels by understanding which anomalies they prevent and how MySQL InnoDB snapshots and locking reads affect concurrent order operations.

      Open lesson →
    • 3.9Idempotency keysLesson · 25 min

      Use a customer-scoped idempotency key to distinguish a completed replay from a request still in progress, preventing checkout retries from creating duplicate orders.

      Open lesson →
    • 3.10POST /v1/orders: idempotent checkoutExercise · 120 min

      You build POST /v1/orders to price menu lines on the server and create an order with its lines, first event and outbox row. A customer-scoped idempotency key makes completed retries return the original order and prevents concurrent duplicates.

      Open exercise →
  3. Module 3: Order lifecycle API

    2 items

    You build an order lifecycle API that applies authorized status changes and exposes order history to the app.

    • 3.11State machines and optimistic lockingLesson · 35 min

      You can model role-authorized transitions and reject stale order writes, giving the next exercise a precise lifecycle and concurrency contract.

      Open lesson →
    • 3.12POST /v1/orders/{id}/events: order lifecycleExercise · 150 min

      You build POST /v1/orders/{id}/events to apply authorized transitions, GET /v1/orders to page the caller's orders, and GET /v1/orders/{id} to return order history. Each applied transition advances the version once and writes its event and outbox row together.

      Open exercise →
  4. Module 4: Kafka event publishing

    3 items

    You build a transactional outbox relay that publishes order changes to Kafka for downstream consumers.

    • 3.13Kafka partitions and groupsLesson · 30 min

      You can trace a keyed order event to its partition, so the relay sends every event for one order to the same place.

      Open lesson →
    • 3.14Transactional outbox writesLesson · 30 min

      You can commit an outbox row with its order change, giving the relay a durable record to publish without a dual-write gap.

      Open lesson →
    • 3.15Outbox relay to order-eventsExercise · 110 min

      You build an outbox relay that reads committed, unsent MySQL rows and publishes Kafka records to each row's stored topic. It preserves event order, marks published rows as sent, and skips rows locked by another transaction.

      Open exercise →
  5. Module 5: Reliable event consumers

    2 items

    You build a notifier worker that consumes order events, records one notification per event, and parks exhausted or unreadable records in a dead-letter topic.

    • 3.16Idempotency and retry handlingLesson · 35 min

      You make event handling safe under redelivery so the notifier can retry failed sends without creating duplicate notifications.

      Open lesson →
    • 3.17Notifier worker with retries and DLQExercise · 130 min

      You build cmd/worker, which consumes order-events and records one notification for each event's order customer. The event_id marker and notification row must commit together so redelivery after a crash cannot duplicate a notification.

      Open exercise →
  6. Module 6: API and worker shutdown

    2 items

    You add coordinated SIGTERM shutdown to the API and notifier worker so both processes stop active work before deployments replace them.

    • 3.18Signal-driven shutdownLesson · 20 min

      You can connect SIGTERM to context cancellation and wait for long-lived goroutines to stop, which both binaries need before closing their clients.

      Open lesson →
    • 3.19API and notifier shutdownExercise · 50 min

      You add coordinated SIGTERM shutdown to the API and notifier, stopping each process cleanly before it exits. Both must exit within 10 seconds, and the API must reject an empty or shorter-than-32-byte JWT_SECRET.

      Open exercise →
  7. Module 7: Order service capacity

    1 items

    You build a workload estimate for the order service and its asynchronous pipeline to identify likely capacity limits before load testing.

    • 3.20Capacity estimationLesson · 50 min

      Estimate the order service's workload so you can identify likely bottlenecks and choose what to measure during load testing.

      Open lesson →
  8. Module 8: Account and outbox extensions

    4 items

    You add optional hardening to accounts and the outbox so refresh sessions remain isolated and background processing stays safe under concurrency.

    • 3.21Refresh families, relay locking, login throttlingLesson · 25 min · Optional

      You can isolate refresh-token sessions, coordinate concurrent outbox relays with FOR UPDATE SKIP LOCKED, and throttle login attempts per IP and email using Redis.

      Open lesson →
    • 3.22POST /v1/auth/refresh: detect token reuseExercise · 60 min · Optional

      You add refresh-token family tracking to POST /v1/auth/refresh so replaying a consumed token revokes the newest token from that login. The same user's other login sessions must remain valid.

      Open exercise →
    • 3.23Concurrent outbox relayExercise · 60 min · Optional

      You build a concurrent outbox relay that claims unsent rows from MySQL and publishes them to Kafka. Competing relays must not publish the same row twice, and a relay that cannot reach Kafka must leave rows available to healthy relays.

      Open exercise →
    • 3.24POST /v1/auth/login: rate limit attemptsExercise · 45 min · Optional

      You add independent per-IP and per-email rate limits to POST /v1/auth/login. The middleware preserves the request body and returns HTTP 429 with rate_limited and Retry-After when either limit is exceeded.

      Open exercise →

Completion checklist

What should be true at the end of the week.

  • Sign up, log in and refresh an account; verify the returned access token and confirm that reusing a rotated refresh token returns 401 invalid_refresh_token.
  • Send 50 concurrent POST /v1/orders requests with the same idempotency key; confirm they create one order.
  • Send an event from the wrong role and confirm 403; send an illegal transition and confirm 409.
  • Place 30 orders, kill the worker with kill -9 while it processes events, then restart it and confirm exactly one notification per event.
  • Fail an event send three times and confirm it appears in order-events.dlq; confirm an unreadable record also goes straight to the dead-letter topic.
  • Send SIGTERM to the API and worker; confirm each exits with status 0 within 10 seconds.

Week requirements

Rules every piece of code this week must follow.

  • Signup and login must return verifiable token pairs; access tokens last 900 seconds, and each refresh rotates the refresh token. Reusing a rotated token returns 401 invalid_refresh_token.
  • Email addresses are trimmed and lowercased; a second signup with the same email returns a conflict, and wrong passwords and unknown emails receive the same response.
  • POST /v1/orders requires an Idempotency-Key of 1 to 36 characters. Replays return the original order, and keys are scoped per customer.
  • Order creation prices selections on the server and writes the order, its lines, its first order event and its outbox row in one transaction.
  • Only the allowed role can apply an order transition; a wrong role returns 403, an illegal transition returns 409, and each applied event creates an outbox row.
  • The relay publishes order events in order, keyed by order id, marks published outbox rows as sent and does not let a row held by another transaction block the remaining rows.
  • The notifier records one notification per event, does not notify twice after redelivery or worker restart, retries failed sends and sends records to the dead-letter topic after three failed attempts. Both binaries exit with status 0 within 10 seconds of SIGTERM, and the API refuses to start without a strong JWT secret.
Authentication, orders and Kafka eventsWeek 3 · 24 items available
Start Module 1: Account authentication
Week 3: Authentication, orders and Kafka events · Learn the Zomato tech stack from scratch