What are in-process domain events, and how do they differ from commands and CRUD notifications?

An in-process domain event is a record of something that has already happened inside one module, published to other modules in the same process. OrderPlaced, PaymentCaptured and ShipmentDispatched are examples. Each is named in the past tense because it states a fact. The module that owns the concept is the only one allowed to publish it. Subscribers can react to the fact, but they cannot veto it or change it.

A command is different. ReserveStock asks a specific module to do something, and that module may refuse. It has one intended recipient, and the sender usually cares about the outcome. A generic EntityUpdated or row-changed notification is different again. It tells subscribers that data moved but not what it means. Every consumer then has to work out the business intent from field diffs, which ties them to the publisher's schema.

Message type Tense Recipients Carries intent Couples to internals
Domain event (OrderPlaced) Past Zero or many Yes No
Command (ReserveStock) Imperative Exactly one Yes Moderately
CRUD notification (OrderUpdated) Past Zero or many No Yes

Only domain events belong on the bus. Commands belong in direct calls through a module's public API, where failures are handled explicitly. CRUD notifications leak the persistence model.

This guide is for teams running a modular monolith with clear module ownership who expect to extract some modules later. The approach is to design the in-process bus as if it were already remote. Treat payloads as serialisable contracts, and assume delivery can be delayed or repeated. If you do that, extracting a module mostly means changing the transport rather than redesigning how modules talk to each other.

Why use an event bus in a modular monolith, and when should you avoid it?

The main benefit is that the publishing module doesn't know who is listening. When Orders publishes OrderPlaced, it never references Invoicing, Loyalty or Analytics. A new subscriber is added by registering a handler, with no change to Orders. Teams stop editing each other's code to wire in side effects, and the dependency graph stays acyclic. Each module also already talks to the others through messages, so extracting one later is mostly a transport change.

Events are the wrong tool when the caller needs an answer. A query such as "what is this customer's credit limit?" or a command whose result decides the next step should be a direct call through the target module's public API. Using publish/subscribe for these hides a synchronous dependency behind asynchronous plumbing. If the monolith will never be split, the extraction argument goes away, and you are left with indirection that doesn't pay for itself.

That indirection has a real cost. Debugging means working out which handlers subscribe to an event rather than reading a stack trace. You need a handler registry you can inspect at startup, and correlation IDs carried from the originating request through every handler's logs. Without them, a failure three handlers downstream is hard to trace back to the request that caused it.

Approach Coupling Answer returned Best for
Domain events Publisher unaware of subscribers No Side effects, cross-module reactions
Public API call Caller depends on callee's interface Yes Queries, decisions needing a result
Shared tables Schema-level, hidden Implicit Avoid. It blocks extraction and bypasses invariants

How do you define event contracts that don't leak a module's internal model?

An event contract is part of a module's public API, just like its service interfaces. Put event types in the module's published contracts package, separate from its domain and persistence code, and make them immutable: set every field at construction and expose no setters. Handlers in other modules can't mutate a shared object, and the publisher can't change it after dispatch.

Every event should carry the same small envelope:

  • Event ID: a unique identifier, so handlers can detect duplicates.
  • Occurred-at timestamp: when the fact happened, not when a handler saw it.
  • Aggregate identifiers: the IDs consumers need to look up or correlate state, such as an order ID and customer ID.

After the envelope, include only the facts consumers actually react to. An OrderPlaced event might carry the order total and currency. It shouldn't carry the full order with line items, addresses and internal status flags.

Never put ORM entities in an event. An entity drags along lazy-loaded relations, persistence annotations and the owning module's table structure. Once another module reads order.Customer.Address.PostalCode through an event, renaming a column becomes a cross-module migration, and nothing in the module graph shows that dependency. Oversized DTOs cause the same problem more slowly, because every extra field is one more thing someone may depend on.

For versioning, additive changes are safe: add optional fields and never repurpose existing ones. If you need to change a field's meaning or remove it, publish a new type such as OrderPlacedV2 alongside the old one. Retire the old type only after every consumer has moved to the new one.

// ordering/contracts/OrderPlaced.java (no imports from ordering.domain or ordering.persistence)
package com.example.ordering.contracts;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;

// A record is immutable: every field is final, set at construction, and has no setter.
public record OrderPlaced(
        UUID eventId,       // unique per event so handlers can drop duplicates
        Instant occurredAt, // when the order was placed, not when a handler saw it
        UUID orderId,       // aggregate identifiers consumers use to look up or correlate state
        UUID customerId,
        BigDecimal total,   // only the facts consumers react to; no line items, addresses or status flags
        String currency) {  // ISO 4217 code, e.g. "EUR"

    public OrderPlaced {
        Objects.requireNonNull(eventId, "eventId");
        Objects.requireNonNull(occurredAt, "occurredAt");
        Objects.requireNonNull(orderId, "orderId");
        Objects.requireNonNull(customerId, "customerId");
        Objects.requireNonNull(total, "total");
        Objects.requireNonNull(currency, "currency");
    }

    // The ordering module maps its entity to plain values here, so the entity never leaves the module.
    public static OrderPlaced of(UUID orderId, UUID customerId, BigDecimal total, String currency, Instant now) {
        return new OrderPlaced(UUID.randomUUID(), now, orderId, customerId, total, currency);
    }
}

// ordering/contracts/OrderPlacedV2.java
// The meaning of the amount changed (tax now included), so this is a new type published
// alongside OrderPlaced. OrderPlaced is retired only after every consumer has switched.
public record OrderPlacedV2(
        UUID eventId, Instant occurredAt, UUID orderId, UUID customerId,
        BigDecimal totalIncludingTax, String currency) {}

Immutable Java records in the ordering module's contracts package: OrderPlaced carries the standard envelope and a minimal payload, and OrderPlacedV2 is published alongside it when the meaning of a field changes.

Building a minimal in-process event bus with DI-registered handlers

The bus needs only two abstractions. The publishing side exposes a single publish(event) operation, so modules depend on the act of announcing a fact and not on who listens. The consuming side implements EventHandler<T> with one method, handle(event: T, context). Keeping both interfaces this narrow makes the in-process bus easy to replace with a remote transport later. A handler written against it never learns whether delivery happened in memory or over a broker.

Register handlers in the DI container keyed by event type, not by publisher. At dispatch, the bus resolves every handler registered for the event's concrete type and invokes each one. Resolving through the container gives handlers their usual dependencies and scoping, so a handler needs no special lifecycle. Avoid matching on base types or wildcards. Dispatch by exact type keeps subscriptions explicit and grep-able.

The context argument carries a correlation ID and a cascade depth. When a handler publishes a follow-up event, the bus copies the correlation ID forward and increments the depth. Every log line includes the event type, handler name, correlation ID and depth, so you can reconstruct one business operation across modules from logs alone.

Set a hard depth limit, such as 3, and fail loudly when it is exceeded. Unbounded cascades hide cycles, like A triggering B triggering A, and make ordering depend on registration order.

Finally, expose a listHandlers() method that returns the full map of event types to handlers. Dump it at startup or in a diagnostics endpoint so you can see who reacts to what before anything runs.

import { randomUUID } from "node:crypto";

interface EventContext { correlationId: string; depth: number; }
interface EventHandler<T> { handle(event: T, ctx: EventContext): Promise<void>; }
type EventType<T> = new (...args: any[]) => T;
type Registration = { name: string; resolve: () => EventHandler<any> };

const MAX_DEPTH = 3; // fail loudly instead of letting A -> B -> A cascade forever

export class InProcessEventBus {
  // Keyed by exact event class, never by publisher, base type or wildcard
  private registry = new Map<EventType<any>, Registration[]>();
  constructor(private log: (fields: Record<string, unknown>) => void) {}

  // `resolve` delegates to the DI container so handlers keep normal scoping
  register<T>(type: EventType<T>, name: string, resolve: () => EventHandler<T>): void {
    this.registry.set(type, [...(this.registry.get(type) ?? []), { name, resolve }]);
  }

  // Handlers pass their own ctx as `parent` so correlation and depth flow forward
  async publish(event: object, parent?: EventContext): Promise<void> {
    const ctx: EventContext = {
      correlationId: parent?.correlationId ?? randomUUID(),
      depth: parent ? parent.depth + 1 : 0,
    };
    const eventType = event.constructor.name;
    if (ctx.depth > MAX_DEPTH) {
      throw new Error(`Cascade depth ${ctx.depth} exceeded for ${eventType} (correlationId=${ctx.correlationId})`);
    }
    for (const { name, resolve } of this.registry.get(event.constructor as EventType<any>) ?? []) {
      this.log({ msg: "dispatch", eventType, handler: name, ...ctx });
      await resolve().handle(event, ctx);
    }
  }

  // Dump at startup or from a diagnostics endpoint to see who reacts to what
  listHandlers(): Record<string, string[]> {
    return Object.fromEntries([...this.registry].map(([t, regs]) => [t.name, regs.map((r) => r.name)]));
  }
}

A minimal in-process event bus that dispatches by exact event type to container-resolved handlers, logs every dispatch with correlation ID and cascade depth, enforces a hard depth limit, and exposes the handler map for diagnostics.

When should handlers run: inside the transaction, after commit, or asynchronously?

The second question is when handlers run. The bus can invoke them at three points, and each one trades consistency against coupling.

Timing Consistency Handler failure reaches publisher? Publisher latency Runtime coupling
Inside the transaction Atomic with the write Yes, it rolls back the publisher's write Includes every handler High
After commit, in memory Eventual, and lost on crash No, the write has already committed Includes handlers unless offloaded Medium
Asynchronous via outbox Eventual, at-least-once No Only the outbox insert Low

In-transaction handlers look safe because everything commits or nothing does. The cost is that a bug in the Notifications module now rolls back an order. A slow query in Loyalty also holds the Orders transaction open, along with its locks. The modules share a failure domain, so you have kept the direct call and only renamed it.

After-commit dispatch removes that coupling, but it opens a gap. Between the commit and the handler finishing, the event exists only in memory. If the process crashes or is redeployed in that window, the order exists and no invoice is ever raised. Nothing records that the event was missed.

Asynchronous handling makes eventual consistency visible to users and the business:

  • Stale reads: a customer may see "points pending" right after checkout. Decide whether the UI should show that state or poll until it resolves.
  • Compensating actions: if inventory reservation fails after the order committed, you cannot roll back. You need an explicit cancel-and-refund flow, and someone has to decide how the customer is told.

How do transactional events and the outbox pattern work together?

Aggregates should not publish anything themselves. Instead, each aggregate records events in a private list as its methods change state. The unit of work collects those lists from every tracked aggregate when it commits. It dispatches them only after the database confirms the commit, and it discards them on rollback. This guarantees that handlers never react to state that was never persisted.

That still leaves a gap. If the process crashes between commit and dispatch, the events are lost. The outbox closes this gap by writing each event as a row in an outbox table inside the same transaction as the state change. The state change and the event then either both persist or neither does.

Aggregate --records--> Unit of Work --single tx--> [ orders | outbox ]
                                                          |
                                     Relay (polls unprocessed rows)
                                                          |
                                     Handlers --> mark row processed

A relay polls for unprocessed rows, dispatches them to handlers, and marks them processed. Because the relay can crash after dispatching a row but before marking it, delivery is at-least-once. This is why the idempotency covered next matters.

The outbox brings ongoing operational work:

  • Cleanup: processed rows accumulate indefinitely unless a scheduled job deletes or archives them.
  • Ordering: the relay must read rows by a monotonic sequence column, not by timestamp. If you run multiple relay instances, they can process rows out of order unless you partition rows by aggregate ID.
  • The poller itself: it needs locking so two instances don't claim the same row, plus backoff on failures and alerting on queue lag.

Illustrative estimate. Assume one engineer, an existing ORM unit of work, and no prior outbox. Building the outbox table, relay, and cleanup job might take 5–8 days. Ongoing maintenance might take 1–2 days per quarter for tuning, investigating stuck rows, and schema changes.

-- PostgreSQL. id gives a monotonic sequence for ordering; do not order by created_at.
CREATE TABLE outbox (
  id           BIGSERIAL PRIMARY KEY,
  aggregate_id UUID        NOT NULL,
  event_type   TEXT        NOT NULL,
  payload      JSONB       NOT NULL,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  processed_at TIMESTAMPTZ            -- NULL until the relay has dispatched it
);
-- Partial index keeps the relay's lookup cheap as processed rows pile up.
CREATE INDEX outbox_unprocessed ON outbox (id) WHERE processed_at IS NULL;

-- Unit of work: the state change and the event row commit or roll back together.
BEGIN;
UPDATE orders SET status = 'placed'
  WHERE id = '3f6c1a2e-0000-4000-8000-000000000001';
INSERT INTO outbox (aggregate_id, event_type, payload)
VALUES ('3f6c1a2e-0000-4000-8000-000000000001', 'OrderPlaced',
        '{"orderId": "3f6c1a2e-0000-4000-8000-000000000001", "total": 4200}');
COMMIT;

-- Relay: claim a batch. SKIP LOCKED stops two pollers from claiming the same row.
-- Concurrent pollers can still dispatch out of order, so partition by aggregate_id
-- or run a single active relay if ordering matters.
BEGIN;
SELECT id, aggregate_id, event_type, payload
  FROM outbox
 WHERE processed_at IS NULL
 ORDER BY id
 LIMIT 100
 FOR UPDATE SKIP LOCKED;
-- ...the application dispatches to handlers here. A crash before COMMIT means redelivery...
UPDATE outbox SET processed_at = now() WHERE id = ANY($1);  -- $1: claimed ids
COMMIT;

-- Scheduled cleanup: without this job, processed rows accumulate forever.
DELETE FROM outbox WHERE processed_at < now() - INTERVAL '7 days';

A PostgreSQL outbox in four steps: the table, a unit of work that writes the state change and the event in one transaction, a relay that claims batches with FOR UPDATE SKIP LOCKED and marks them processed, and a cleanup job for old rows.

How do you make handlers idempotent, enforce boundaries, and test the setup?

Idempotency

Once the outbox relay exists, handlers get at-least-once delivery. A crash between handling an event and marking it processed means the same event runs again. Each handler should record the event ID in a processed-events table, keyed by handler name and event ID, inside the same transaction as its own writes. A duplicate then fails the unique constraint and is skipped. If the handler's effect already has a natural key, an upsert on that key is enough, and you don't need the extra table. One example is "one loyalty account per customer ID."

Boundaries

Event contracts only decouple modules if nothing else couples them. Add architecture tests that fail the build when one module imports another module's internal namespaces, or when one module's repository touches another module's tables. Build-level module dependency rules are stricter still, because forbidden references don't compile at all. Either check is cheaper than a code review that someone has to remember to do.

Testing

  • Unit-test handlers with a fabricated event and in-memory fakes for their own module's ports.
  • Assert on published events in command tests by capturing what the bus received. Don't assert on downstream side effects.
  • Integration-test against a real database. A committed transaction should produce outbox rows and handler effects. A rolled-back transaction should produce neither.

Why this saves time

Each forbidden dependency these checks catch is one less thing to untangle when you extract the module. That untangling happens later, under deadline, across a network boundary.

-- PostgreSQL. One row per (handler, event): a redelivered event cannot be applied twice.
CREATE TABLE processed_events (
  handler_name text        NOT NULL,
  event_id     uuid        NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (handler_name, event_id)
);

-- Dedup-table approach: claim the event and apply the effect in one transaction.
BEGIN;
WITH claimed AS (
  INSERT INTO processed_events (handler_name, event_id)
  VALUES ('loyalty.award_points_on_order_placed',
          '7c9e6679-7425-40de-944b-e07fc1f90ae7')
  ON CONFLICT DO NOTHING  -- a duplicate inserts nothing
  RETURNING event_id
)
-- The effect runs only if the claim succeeded, so a retry is a no-op.
INSERT INTO loyalty_ledger (customer_id, order_id, points)
SELECT 'cust-1042', 'ord-88731', 120
FROM claimed;
COMMIT;  -- a rollback releases the claim, and a retry runs the handler again

-- Natural-key approach: the effect is already unique per customer, so no dedup table.
CREATE TABLE loyalty_accounts (
  customer_id text        PRIMARY KEY,  -- one loyalty account per customer
  tier        text        NOT NULL DEFAULT 'basic',
  opened_at   timestamptz NOT NULL DEFAULT now()
);

-- Handler for CustomerRegistered: running it twice leaves the same single row.
INSERT INTO loyalty_accounts (customer_id)
VALUES ('cust-1042')
ON CONFLICT (customer_id) DO NOTHING;

This PostgreSQL example shows two ways to make a handler idempotent: the handler claims each event in a processed-events table in the same transaction as its own write, or it upserts on a natural key, so an at-least-once redelivery has no additional effect.

What does extracting a module look like when the event bus becomes remote?

Extraction starts with the publishing side. Callers keep the same publish interface, and only its implementation changes: instead of dispatching to handlers in the same process, it does nothing on the request path, and the outbox relay picks up committed rows and sends them to a broker. Because events were already written to the outbox inside the business transaction, the delivery guarantee does not change. The relay now crosses a network instead of calling a local dispatcher.

The extracted module leaves with everything it owns: its handlers, its tables, and its processed-event store. That store has to travel with the module. Deduplication only works if the record of handled event IDs sits next to the state those handlers change, and the broker will redeliver.

What still changes

The transport is new, so its failure modes are new too. Handlers that never saw timeouts will now see partitions, consumer lag and redelivery after a crash. Serialization becomes a real boundary. In-process, a contract type could be passed by reference. Now it needs an explicit wire format and a versioning rule. Contract ownership also has to be decided: the publishing team owns the schema, and consumers can no longer edit it in the same pull request.

Concern Events already in place Direct coupling
Call sites Unchanged Rewritten as API calls or events
Data access Module owns its tables Shared tables must be split
Delivery guarantees Outbox already exists Designed from scratch
Main new work Transport, serialization, schema ownership All of that plus finding every hidden dependency

With events in place, the remaining effort is bounded by the transport. With direct coupling, the effort depends on how many dependencies you find, and you discover those as you go.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to in-process domain events, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.