Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 33 ยท Practice and Review

Practice: Exercises with Solutions

Ten Medusa exercises with worked solutions: model design, price resolution, workflow rollback, route validation, idempotent events, variants, stock, links, retries and cron.

Reading about modules, workflows and events is one thing; writing the logic yourself is how it sticks. This lesson has ten exercises, one for each big idea in the track. Every exercise comes with a runnable solution you can edit and break.

A reminder about what is real here. Medusa itself needs a Node server, Postgres and often Redis, so it cannot run on this site, and the real code of your own modules, routes and workflows is always read-only in lessons. The solutions below are stand-ins: small plain-JavaScript functions that reproduce the rule each Medusa feature follows, so you can practice the logic without the framework. When you move to a real project, the same logic goes inside a service method, a workflow step, a route handler or a subscriber.

Try each exercise on your own first. Write down what the function should receive and return, then compare with the solution.

flowchart LR
    M["1 Model design"] --> P["2 Price resolution"]
    P --> W["3 Workflow rollback"]
    W --> R["4 Route validation"]
    R --> E["5 Idempotent events"]
    E --> V["6 Variants"]
    V --> S["7 Stock reservation"]
    S --> L["8 Links"]
    L --> D["9 Retries"]
    D --> C["10 Cron"]

The exercises follow the track: data, APIs, workflows, events, and finally background work.

Exercises 1 and 2: models and prices

Exercise 1: model design. You are adding a review model to a custom module (see Custom Modules and Data Models). Write defineModel(name, properties) that returns the list of table columns. Rules: the model must declare a primary key called id; property names must be snake_case; allowed types are text, number, boolean, json, dateTime; and the function adds created_at, updated_at and deleted_at automatically, as the real model.define does. Invalid models must throw an error that names the problem.

Exercise 2: price resolution. Prices live in a price set (see Prices, Currencies and Regions). Write resolvePrice(prices, context) that picks the amount for a currency, a region and a quantity. A price matches when its currency equals the context currency, its region (if it has one) equals the context region, its minQuantity (default 1) is not above the quantity, and its price list (if it has one) is active. Among matches, prefer a price-list price, then a region-specific price, then the highest minQuantity. Amounts are integers in the smallest currency unit.

Node.js Solutions 1 and 2: a model builder and a price resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the real Pricing Module is more general: it can match many rule types, not only region, and it can compute the winner in the database. The ordering idea (more specific rules beat less specific ones, and campaign prices beat base prices) is the part worth remembering. Prices as integers are explained in Money as Integers.

Exercises 3 and 4: workflows and routes

Exercise 3: workflow rollback. Write runSteps(steps, input). Each step has name, run(state) and an optional undo(state). Run the steps in order, storing each step's return value in state[name]. If a step throws, call undo for the steps that already finished, in reverse order, and return { status: "rolled_back", failedAt, log }. If all succeed, return { status: "done", state, log }. This is the idea behind compensation in Compensation, Rollback and Long-Running Workflows.

Exercise 4: route validation. A custom route accepts a JSON body. Write validateBody(schema, body) for a schema such as { email: { type: "string", required: true, pattern: /@/ }, rating: { type: "number", min: 1, max: 5 } }. Return { ok: true, value } or { ok: false, errors } with one message per problem. Choose a strict policy: unknown keys are an error. The real route would use Zod through a middleware (see Custom API Routes and Middleware).

Node.js Solutions 3 and 4: a saga runner and a body validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercises 5 and 6: events and variants

Exercise 5: an idempotent subscriber. Event buses deliver at least once, so the same event can arrive twice (see Events and Subscribers). Write createHandler(award) that gives loyalty points when an order.placed event arrives, but ignores an event whose id it has already processed. Show that delivering the same event twice awards points once.

Exercise 6: variants from options. Write generateVariants(baseSku, options) that builds every combination of option values (the cartesian product, see Products, Variants and Options). Each variant gets a SKU made of the base SKU and the upper-cased values joined with dashes. Throw if two variants end up with the same SKU, because SKUs must be unique.

Node.js Solutions 5 and 6: a deduplicating handler and variant generation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The subscriber must remember processed ids somewhere durable in a real project (a table with a unique constraint is the usual choice), because an in-memory Set is lost when the process restarts. The track on Idempotency explains why.

Exercise 7: reserving stock by sales channel. Levels are stored per location. A sales channel may only use its own locations (see Inventory, Stock Locations and Sales Channels). Write reserveAll(lines, channel). For each line, take the first location of the channel with enough free stock and reserve it. If any line cannot be satisfied, release everything reserved so far and return { ok: false, missing }.

Exercise 8: querying through a link. Reviews live in their own module and are connected to products by a link table (see Module Links). Write graph({ products, reviews, links }, productId) that returns the product with a reviews array, including only approved reviews. Use only the link table to connect them.

Node.js Solutions 7 and 8: an all-or-nothing reservation and a link join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercises 9 and 10: retries and cron

Exercise 9: retries and a dead-letter list. Write deliver(event, handler, maxAttempts) that calls the handler until it succeeds or the attempts run out. It should compute the waiting time before each retry (1 second, then doubling) without really waiting, so the result is deterministic. After the last failure, push the event and its error onto a deadLetters list.

Exercise 10: a cron matcher. Scheduled jobs use cron expressions (see Scheduled Jobs). Write matches(expression, date) for five fields (minute, hour, day of month, month, day of week) that supports *, a number, a range a-b, a step */n and comma lists. Use UTC time.

Node.js Solutions 9 and 10: dead letters and a cron matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The cron matcher is simplified on purpose: it treats * as 0 to 59 for every field, so it works for minutes but does not validate each field's real range. The real scheduler uses a proper cron library.

How to keep practicing

Pick one exercise and extend it. Give defineModel a relations option, make resolvePrice return the reason for its choice, or let runSteps retry a failing step twice before rolling back. Then try the same change in a real Medusa project: a workflow step with a compensation function, or a route with a Zod schema. The stand-ins show the rule; only a real server shows the wiring.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In exercise 2, why does a price-list price beat a region price in the sort order?

    A price list is an explicit override such as a sale. When it is active it should win over ordinary base or region prices. It does not have to be lower, so the order is a rule, not a comparison of amounts.
  2. 2. What must a rollback do with the steps that finished before a failure?

    Later steps may depend on earlier ones, so compensation walks backwards, like unwinding a stack.
  3. 3. Why is an in-memory Set not enough for a real idempotent subscriber?

    A restart or a second instance forgets the ids, so a repeated event would be processed again. Use durable storage such as a table with a unique key.
  4. 4. What should reserveAll do when the third line of an order is out of stock?

    A cart completes all or nothing. Partial reservations would lock stock for an order that never exists, and other channels' locations are off limits.
  5. 5. Which statement about the dead-letter list is correct?

    Retries handle temporary problems. Events that still fail are parked with their error instead of being lost or retried forever.

Summary

  • Each Medusa feature follows a small rule: specific prices win, failed workflows compensate in reverse, subscribers tolerate duplicates, and reservations are all or nothing.
  • Stand-ins let you practice these rules without a server; real code puts the same logic in services, steps, routes and subscribers.
  • Validate input at the edge, keep module data connected only through links, and keep retry behavior bounded with a dead-letter place.
  • Cron and scheduling logic is easy to get subtly wrong, so test it with fixed dates.

Next, rehearse short answers in Medusa Interview Questions.