Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 33 ยท Events and Background Work

Events and Subscribers

React to things that happen in Medusa with events and subscribers: event names, payloads, emitting from workflows, Redis vs local bus, and idempotent handlers.

When an order is placed, a lot of work follows: send a confirmation email, tell the warehouse, update a search index, award loyalty points. Putting all of that inside the "place order" code would make it slow, fragile and hard to extend. Medusa instead emits an event and lets any number of subscribers react. The code that placed the order neither knows nor cares who is listening.

This lesson covers the event bus, how events are named and emitted, how to write and configure a subscriber, the difference between the local and Redis event bus, and the most important property of a handler: it must be safe to run twice. The Medusa code is read-only; a runnable event bus with retries models the behavior.

The idea

flowchart LR
    W["Workflow<br/>places order"] -->|"emit order.placed"| EB["Event bus"]
    EB --> S1["Subscriber:<br/>send email"]
    EB --> S2["Subscriber:<br/>award points"]
    EB --> S3["Subscriber:<br/>sync to ERP"]

The emitter publishes one event; every registered subscriber receives its own copy.

An event is a name plus a small data payload. Medusa's built-in events follow a <thing>.<what happened> pattern such as order.placed, product.created, customer.created or product.updated. The payload usually carries ids, not whole records: for order.placed you receive { id: "order_..." } and load whatever you need with Query. Check the reference for the exact event names of your version; custom events are just strings you choose.

Events are the right tool for reactions that can happen after the main operation and must not block or fail it. If the reaction must succeed or fail together with the operation, use a workflow hook instead (Hooks and Built-in Workflows).

Writing a subscriber

A subscriber is a file in src/subscribers/ that default-exports an async function and exports a config naming the events it handles. This is real, read-only Medusa code:

TypeScript
// src/subscribers/order-placed.ts
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"

export default async function orderPlacedHandler({
  event: { data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const query = container.resolve(ContainerRegistrationKeys.QUERY)
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER)

  const { data: orders } = await query.graph({
    entity: "order",
    fields: ["id", "email", "total"],
    filters: { id: data.id },
  })

  logger.info(`Order ${orders[0].id} placed by ${orders[0].email}`)
}

export const config: SubscriberConfig = {
  event: "order.placed",
}

event can also be an array of names to handle several events in one file. The handler receives the event (name and data) and the container, so everything from Architecture: Modules, Workflows and the Container applies. Inside a subscriber it is common to run a workflow, for example "send the confirmation email" or "create the loyalty entry".

Keep subscribers thin: load what you need, then delegate to a workflow so the work has steps, compensation and tests.

Emitting events

Built-in workflows emit their own events. For your own workflows, add the emit step at the end of the plan so the event is only sent when everything before it succeeded:

TypeScript
import { emitEventStep } from "@medusajs/medusa/core-flows"

// inside createWorkflow(...)
emitEventStep({
  eventName: "review.approved",
  data: { id: review.id },
})

Outside workflows, resolve the event bus module and call emit with a name and data. Prefer the workflow step: it integrates with the engine so the event is released only if the workflow commits.

Local versus Redis event bus

The event bus is a module, so its implementation is configurable in medusa-config.ts.

Event bus How it works Use it for
Local (default) In process, in memory; events are lost if the process stops Development and tests
Redis Events are queued in Redis and consumed by workers, with retries Production

With the local bus a crash can lose events and every server instance would only see its own. In production, use the Redis event bus module (@medusajs/medusa/event-bus-redis with your redisUrl) so events survive restarts and can be processed by dedicated worker instances (Deploying Medusa).

At least once, so be idempotent

A durable queue gives you at-least-once delivery: if a handler crashes or times out, the event is delivered again. That means your subscriber can run twice for the same event. The rules of thumb match Idempotency:

  • Record that you handled an event, keyed by event or by the thing it describes (order_id), and skip duplicates.
  • Prefer "set to" operations over "add to": set points_awarded = true rather than blindly adding 100 points.
  • Call outside APIs with an idempotency key.
  • Do not depend on ordering or on exactly one delivery. Two events for the same object may arrive in either order.
  • Handle "not found" gracefully: the record may have been deleted by the time the event is processed.

Webhooks from outside systems have the same delivery guarantee, so the pattern is the same as in Webhooks and Signatures.

Stand-in 1: an event bus with retries

This stand-in has the essential bus behaviors: named events, multiple subscribers, and a bounded number of retries for a handler that throws. A failing subscriber does not affect the others, and the emitter never sees the failure. It is a model, not Medusa's event module.

JS An event bus with retries and isolated subscribers

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

No output.

The email subscriber succeeded on its third attempt, the log subscriber was unaffected, and the ERP subscriber ended up in the dead-letter list after exhausting its attempts. Real queues keep such failed jobs for inspection and replay; watching for them is part of running Medusa in production.

Stand-in 2: an idempotent handler

A retried or duplicated event must not award points twice. This stand-in records processed event keys and sets state instead of adding blindly.

JS Handling a duplicate delivery safely

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

No output.

In a real subscriber the processed record lives in the database, ideally written in the same transaction as the change so a crash cannot separate the two.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an event payload typically contain in Medusa?

    Payloads are small, for example an object holding only the order id. Subscribers load the data they need with Query.
  2. 2. Which statement about delivery is correct for a durable event bus?

    Retries after crashes or timeouts cause duplicates. Handlers must be idempotent.
  3. 3. When should you prefer a workflow hook over a subscriber?

    Hooks run inside the workflow and can roll it back. Subscribers run afterwards and cannot undo the operation.
  4. 4. Why use the Redis event bus in production?

    The local bus is in-memory, so events can be lost. Redis queues them and supports retries and separate worker processes.

Summary

  • Events announce that something happened; subscribers in src/subscribers/ react through a default-exported function and a config with the event name.
  • Payloads carry ids; load details with Query, and delegate real work to workflows.
  • Emit custom events with emitEventStep at the end of a workflow.
  • The local bus is for development; use the Redis event bus in production for durability and workers.
  • Delivery is at least once, so make handlers idempotent and watch for events that exhaust their retries.

Next: Scheduled Jobs