Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 33 ยท Getting Started

Architecture: Modules, Workflows and the Container

Understand the layers of Medusa 2: API routes, workflows, modules and the data layer, how the dependency-injection container works, and how a request flows.

Medusa 2 looks different from most Node backends because it is organized around a few strict ideas. Code is split into modules that own their own data, multi-step operations are written as workflows, and everything finds everything else through a dependency-injection container. Once you see how these layers stack, the rest of the framework stops feeling magical.

In this lesson you learn the four layers, what the container is and how resolve() works, why modules are isolated, and how a single request travels through the system. The real code is read-only; two runnable stand-ins build a mini container and a mini request pipeline so you can watch the mechanics.

The four layers

flowchart TD
    R["API routes and middlewares<br/>src/api"] --> W["Workflows and steps<br/>src/workflows"]
    R --> Q["Query<br/>read data"]
    W --> MOD["Modules and their services<br/>product, cart, order, yours"]
    Q --> MOD
    MOD --> DB[("Data layer<br/>Postgres tables per module")]

Routes call workflows to change data and Query to read it; both reach data through modules.

  1. API routes receive HTTP requests, check authentication, validate the body and decide what to do. They should stay thin.
  2. Workflows hold business operations that touch more than one thing, such as "create a product and its prices and inventory". Each workflow is a list of steps that can be rolled back (Workflows and Steps).
  3. Modules are the units that own data and logic for one area. A module has data models, a service with methods like createProducts, and its own migrations.
  4. The data layer is Postgres. Each module owns its tables. Other modules never query them directly.

A rule of thumb: read through Query (Query: Fields, Filters and Pagination), write through workflows, and call a module's service directly only for simple, single-module actions.

What is a module?

A module is a self-contained package of data models plus a service. The built-in Product module knows about products, variants and options. It does not know about carts or orders. The Cart module stores variant_id strings, not product objects.

This isolation is deliberate:

  • You can replace a module, for example swap the Payment or Notification implementation, without touching the others.
  • You can scale or even deploy modules separately later.
  • You can add a custom module (say, product reviews) without altering core tables.
  • Upgrades are safer because modules cannot depend on each other's table layout.

Records in different modules are connected by links and read together by Query, which you meet in Module Links.

The dependency-injection container

Instead of importing service classes directly, Medusa code asks a container for them by name. The container is a registry: during startup Medusa registers every module's service, the Query tool, the logger, the event bus and more, each under a string key. Constants such as Modules.PRODUCT hold those keys so you do not type them by hand.

In a real API route (read-only) it looks like this:

TypeScript
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const productService = req.scope.resolve(Modules.PRODUCT)
  const products = await productService.listProducts({}, { take: 5 })
  res.json({ products })
}

req.scope is the container for this request. Calling resolve(key) returns the registered instance, or throws if nothing is registered under that key. Why bother?

  • Swappability. Code that resolves Modules.NOTIFICATION works with whichever provider is configured.
  • Testability. A test can register a fake service under the same key.
  • Lifetimes. Some registrations are singletons (one instance for the whole server); others are created per request or per workflow run so they carry request-specific state.

The same resolve call appears inside workflow steps (container.resolve(...)), subscribers and jobs, so you learn it once.

Following a request

Take GET /store/products and trace what happens:

  1. The HTTP layer matches the URL to a route file and runs global and route middlewares in order (CORS, publishable-key check, authentication, validation).
  2. A request-scoped container is attached as req.scope.
  3. The route handler resolves what it needs and either runs a workflow or asks Query for data.
  4. Query reads from the modules involved and joins the results through links.
  5. The handler returns JSON; errors thrown on the way are turned into a consistent error response.

For writes, step 3 is usually a workflow. If a later step throws, earlier steps run their compensation functions, so the database is not left half-changed. Compensation, Rollback and Long-Running Workflows covers that.

Stand-in 1: a mini container

Real containers also manage lifetimes and scoping. This stand-in keeps just the core contract: register by key, resolve by key, fail loudly when a key is missing, and create a child scope that inherits parent registrations and can add its own.

JS A container with resolve() and request scopes

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

No output.

Stand-in 2: a mini request pipeline

This second stand-in strings together middlewares, a route handler, a "workflow" that rolls back on failure and a module. It is much simpler than Medusa's, but the order of events is the same: middlewares first, handler second, workflow steps inside it, and an error handler that turns exceptions into responses.

JS Middlewares, handler, workflow and module

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

No output.

The last request created a product, failed in the next step, and the compensation removed it again. Only "Tee" remains.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do Medusa modules not query each other's tables?

    Isolation is a design choice. Modules communicate through IDs, links and Query, so one module's table layout never becomes another module's dependency.
  2. 2. What does req.scope.resolve(Modules.PRODUCT) return?

    The container maps keys to registered services. Resolving returns the instance registered for that key, or throws when nothing is registered.
  3. 3. Where should multi-step business operations that touch several modules usually live?

    Workflows give each step an optional compensation function, so a failure part-way can undo earlier steps. Route handlers stay thin.
  4. 4. In which order do the main parts of a write request run?

    Middlewares run first (CORS, auth, validation), then the handler, which runs a workflow whose steps call module services.

Summary

  • Medusa 2 has four layers: API routes, workflows, modules and a Postgres data layer.
  • Modules own their data models and service and are isolated from each other; links and Query connect their records.
  • The container maps string keys to services; resolve() returns them, and scopes give each request its own view.
  • A write request flows through middlewares, the route handler, a workflow and module services, with compensation on failure.
  • The stand-ins reproduce the mechanics, not Medusa's actual implementation.

Next: The Commerce Modules