What are in-process domain events and why use them in a monolith?

An in-process domain event is an immutable record of something that already happened in the domain, named in the past tense: OrderPlaced, PaymentCaptured, CustomerEmailChanged. The module that owns the state change raises it. Handlers in other modules, running in the same process and usually the same call stack, react to it. No network hop or broker is involved, and no serialization is required.

The main reason to use them is to keep modules from depending on each other. Without events, the Ordering module calls Inventory, Billing and Notifications directly. Every new side effect then means editing Ordering and adding another dependency to it. With events, Ordering states a fact and does not know who listens. New behaviour arrives as a new handler, and the publishing code stays the same.

This matters most for teams running a modular monolith with several bounded modules, where cross-module side effects keep growing and direct calls are starting to form cycles.

Aspect Domain event Command Integration event
Intent Announce a fact Request an action Announce a fact to other systems
Naming Past tense (OrderPlaced) Imperative (PlaceOrder) Past tense, versioned contract
Receivers Zero or more Exactly one Zero or more
Process boundary Same process Usually same process Crosses processes or services
Delivery guarantee In-memory unless persisted, so lost on crash Synchronous result or error At-least-once via broker or outbox

How does an in-process event dispatcher work?

A dispatcher needs four parts:

  • An event type: an immutable record named in the past tense, such as OrderPlaced, carrying IDs and the facts consumers need.
  • A handler interface: a single handle(event) method, generic over the event type it accepts.
  • A registry: a map from event type to a list of handlers. The DI container builds it at startup by collecting every registered handler implementation.
  • A dispatch loop: for each event, look up its type in the registry and call each handler in turn.

Aggregates do not call the dispatcher. When Order.place() succeeds, it appends an OrderPlaced to a private list of pending events and returns. This keeps domain code free of infrastructure. It also stops side effects from firing during construction, rehydration from storage, or a failed validation path. After the unit of work commits, the application layer collects pending events from every tracked aggregate, clears the lists, and passes the events to the dispatcher. Section 3 covers why commit timing matters.

request
  -> application service
       -> aggregate.place()   records OrderPlaced in pending list
  -> unit of work commits
  -> drain pending events
  -> dispatcher (registry lookup)
       -> Billing.OnOrderPlaced
       -> Notifications.OnOrderPlaced

Handlers in other modules should import only the event contract, never the Order aggregate, its repository, or its internal types. If a handler reaches into the publisher's internals, a refactor in Orders can break Billing even though no contract changed. At that point the event provides no decoupling and only hides a direct dependency between the modules.

// Contract module: the only thing other modules import from Orders.
export interface OrderPlaced { readonly type: "OrderPlaced"; readonly orderId: string; readonly totalCents: number }
type DomainEvent = OrderPlaced; // union grows as new events are added

interface Handler<E extends DomainEvent> { handle(event: E): Promise<void> }

// Registry: filled once at startup by the DI container from every registered handler.
class Dispatcher {
  private handlers = new Map<string, Handler<any>[]>();
  register<E extends DomainEvent>(type: E["type"], h: Handler<E>): void {
    this.handlers.set(type, [...(this.handlers.get(type) ?? []), h]);
  }
  async dispatch(events: DomainEvent[]): Promise<void> {
    for (const e of events)
      for (const h of this.handlers.get(e.type) ?? []) await h.handle(e);
  }
}

// Aggregate records facts; it never sees the dispatcher or any infrastructure.
class Order {
  private pending: DomainEvent[] = [];
  constructor(readonly id: string, private status = "draft") {} // rehydration emits nothing
  place(totalCents: number): void {
    if (this.status !== "draft") throw new Error("order already placed"); // failed path: no event
    this.status = "placed";
    this.pending.push({ type: "OrderPlaced", orderId: this.id, totalCents });
  }
  pullEvents(): DomainEvent[] { const e = this.pending; this.pending = []; return e; }
}

// Billing module: depends on the OrderPlaced contract only, not on Order or its repository.
class BillingOnOrderPlaced implements Handler<OrderPlaced> {
  async handle(e: OrderPlaced): Promise<void> { console.log(`invoice order ${e.orderId}: ${e.totalCents}`); }
}

// Application service: mutate, commit, then drain and dispatch.
async function placeOrder(uow: { commit(): Promise<void> }, d: Dispatcher, order: Order): Promise<void> {
  order.place(4999);
  await uow.commit();
  await d.dispatch(order.pullEvents());
}

A minimal in-process dispatcher in which the Order aggregate records OrderPlaced in a private list, the application service drains that list after the unit of work commits, and a Billing handler that depends only on the event contract receives the event.

Should you dispatch events before or after the transaction commits?

Dispatch timing determines what an event failure can break, so decide it per handler rather than once for the whole dispatcher.

Dispatching before commit runs handlers inside the publisher's transaction. Their writes commit or roll back together with the core change, but a bug in an unrelated module now aborts the order. Every handler's work also extends the transaction, so row locks are held longer and contention increases under load.

Dispatching after commit isolates the core operation from handler failures. The cost is a gap: if the process crashes or is redeployed between the commit and dispatch, the side effect is lost and nothing records that it was missed.

A workable rule is to run invariants and same-database consistency updates (counters, projections that must match) before commit. Emails, notifications, cache invalidation and external API calls belong after commit or behind an outbox, because none of them can be rolled back.

Mode Added latency Errors reach caller Request context (user, tenant) Ordering Lost on process exit
Before-commit sync Yes, inside the transaction Yes, rolls back Available Preserved No, atomic
After-commit sync Yes, after the transaction Yes, but data already committed Available Preserved Yes, in the gap
After-commit async in-memory Minimal No, must be logged Must be copied explicitly Not guaranteed across workers Yes, the queue is volatile
Outbox Minimal No, retried Must be serialized Per-stream if designed for it No

How do you make in-process domain events durable with a transactional outbox?

The outbox row closes the gap the in-memory queue leaves open. In the same transaction as the business change, write each event to an outbox table in the monolith's own database. If the transaction rolls back, the event never existed. If it commits, the event survives a crash because it is stored like any other row.

A workable table has these columns:

  • id (UUID, also used as the event ID)
  • event_type
  • schema_version
  • payload (JSON or text)
  • occurred_at
  • status (pending, processed, dead)
  • attempts
  • next_attempt_at
  • last_error

An index on (status, next_attempt_at) keeps the polling query cheap.

The polling worker runs this loop:

  1. Claim a batch of due pending rows. Where the database supports it, use row locking that skips rows other workers have already locked, so several workers can run without contention.
  2. Deserialize each row and dispatch it to its handlers.
  3. On success, mark the row processed.
  4. On failure, increment attempts, record last_error, and push next_attempt_at out with exponential backoff.
  5. Once attempts exceeds the limit, set the row to dead so a person can inspect it.

This gives at-least-once delivery, not exactly-once. A worker can dispatch an event and crash before marking the row processed. Handlers must therefore be idempotent. A common approach is to insert (handler_name, event_id) into a processed-events table with a unique key, in the same transaction as the handler's side effect. A duplicate insert then signals "already handled."

Rows can wait in the table for hours, or sit in dead for weeks. They must stay readable as contracts change. Store schema_version, favor additive changes, and upcast old payloads when you read them.

The cost is real. Polling, retry tuning, dead-letter triage and idempotency bookkeeping are the operational work a broker would otherwise do. You now run that work inside your own codebase.

-- Outbox: written in the same transaction as the business change.
CREATE TABLE outbox (
  id              UUID PRIMARY KEY,          -- doubles as the event ID
  event_type      VARCHAR(200) NOT NULL,
  schema_version  INT NOT NULL,              -- lets readers upcast old payloads
  payload         TEXT NOT NULL,             -- serialized JSON
  occurred_at     TIMESTAMP NOT NULL,
  status          VARCHAR(16) NOT NULL DEFAULT 'pending',  -- pending | processed | dead
  attempts        INT NOT NULL DEFAULT 0,
  next_attempt_at TIMESTAMP NOT NULL,
  last_error      TEXT
);
CREATE INDEX ix_outbox_due ON outbox (status, next_attempt_at);

-- Idempotency: one row per (handler, event), inserted with the handler's side effect.
CREATE TABLE processed_events (
  handler_name VARCHAR(200) NOT NULL,
  event_id     UUID NOT NULL,
  PRIMARY KEY (handler_name, event_id)       -- duplicate insert = already handled
);

-- Worker step 1: claim due rows inside a transaction.
-- SKIP LOCKED (PostgreSQL, MySQL 8+) lets several workers poll without blocking.
SELECT id, event_type, schema_version, payload
FROM outbox
WHERE status = 'pending' AND next_attempt_at <= CURRENT_TIMESTAMP
ORDER BY next_attempt_at
LIMIT 50
FOR UPDATE SKIP LOCKED;

-- Step 3, success:
UPDATE outbox SET status = 'processed' WHERE id = :id;

-- Step 4/5, failure: back off exponentially (PostgreSQL interval syntax);
-- past the limit (assumed 10 here), park the row as dead for a human.
UPDATE outbox
SET attempts = attempts + 1,
    last_error = :error,
    next_attempt_at = CURRENT_TIMESTAMP + (POWER(2, attempts) * INTERVAL '1 second'),
    status = CASE WHEN attempts + 1 >= 10 THEN 'dead' ELSE 'pending' END
WHERE id = :id;

An outbox table, a processed-events table for idempotent handlers, and the claim, success and retry/dead-letter statements a polling worker runs, written in PostgreSQL-flavored SQL.

How should modules, contracts and errors be organized in a modular monolith?

Put each event contract in the publishing module's public API, or in a small shared contracts module if several modules publish. A contract is a plain data type with no references to entities, repositories or ORM sessions. That rule stops a handler from lazily loading another module's tables. If a handler needs more data, the publisher should add it to the payload, or the handler should call the owning module's public query interface. Evolve contracts additively. New optional fields are safe. Renames, removals and meaning changes need a new event type that you publish alongside the old one until every handler has migrated.

Error policy

Decide the policy once and enforce it in the dispatcher:

  • Before-commit handlers take part in the transaction, so a failure aborts the originating operation.
  • After-commit handlers run in isolation. One handler's failure is logged with the event ID and handler name, and the other handlers still run. The failed handler is retried with backoff and dead-lettered after a fixed number of attempts.

Cascades

A handler that raises events can recurse. That produces deep stacks, ordering that depends on which handler ran first, and database round-trips nobody planned for. To avoid this, queue nested events and drain the queue after the current handler finishes. Also cap the cascade depth so that a cycle fails loudly instead of looping.

With these boundaries in place, moving to a broker is a mechanical change. You replace the dispatcher or the outbox relay with a publisher to the broker, and the contracts and handlers stay as they are.

How do you test and observe event-driven code inside a monolith?

Testing at three levels

Most logic should be tested without a dispatcher. Call a method on the aggregate and assert on the events it recorded. A typical test creates an order, calls order.cancel(reason), and checks two things: order.pulledEvents() contains exactly one OrderCancelled with the expected order ID and reason, and a second call to cancel records nothing. These tests are fast, and they treat recorded events as part of the aggregate's public behavior.

Test each handler in isolation by constructing the event directly from its contract type. Avoid triggering it through the publishing module. This keeps the subscriber's tests from depending on the publisher's internals, and it catches handlers that rely on fields the contract does not guarantee.

Keep a small set of integration tests for the parts that unit tests cannot reach:

  • A rollback path, proving that after-commit handlers never run and that no outbox row survives.
  • A successful commit, proving that after-commit handlers run only once the data is visible.
  • Dispatch ordering, where handlers depend on it.

Observability

Events make control flow implicit, so the logs have to make it explicit again. Generate a correlation ID at the request edge. Carry it through synchronous handlers, store it on each outbox row, and restore it in the async worker that processes the row. For every handler invocation, log:

  • event name
  • event ID
  • handler name
  • correlation ID
  • outcome and duration

With these fields, one query reconstructs the full chain of work a single request caused.

from dataclasses import dataclass

@dataclass(frozen=True)
class OrderCancelled:
    order_id: str
    reason: str

class Order:
    def __init__(self, order_id):
        self.id = order_id
        self.status = "placed"
        self._events = []

    def cancel(self, reason):
        if self.status == "cancelled":
            return  # idempotent: a repeat cancel changes nothing and records nothing
        self.status = "cancelled"
        self._events.append(OrderCancelled(self.id, reason))

    def pulled_events(self):
        # Hand recorded events to the caller and clear them so each is dispatched once
        events, self._events = self._events, []
        return events

# No dispatcher, database or handlers: the recorded events are the observable behavior
def test_cancel_records_exactly_one_event():
    order = Order("ord-1001")
    order.cancel("customer_request")
    assert order.pulled_events() == [OrderCancelled("ord-1001", "customer_request")]

def test_second_cancel_records_nothing():
    order = Order("ord-1001")
    order.cancel("customer_request")
    order.pulled_events()  # drain the first event
    order.cancel("customer_request")
    assert order.pulled_events() == []

A minimal aggregate with pytest-style unit tests that assert on the domain events it records. The tests check that a first cancel records exactly one OrderCancelled and a repeated cancel records nothing.

When should you avoid in-process domain events, and what are the alternatives?

Events are not free decoupling. Skip them in three situations.

Small codebase, one team. If the billing module must react to an order, a call through billing's public interface is simpler and more honest. The dependency shows up in the signature, the stack trace shows the path, and the compiler flags breakage. An event hides the same coupling.

Flows that need one readable description. Checkout, payment, fulfilment and their compensations spread across handlers become hidden choreography. Nobody can answer "what happens after checkout?" without grepping for subscribers. Put that flow in an orchestrating application service or a process manager.

Broker-grade requirements. Replay, fan-out to other services, consumer lag visibility and backpressure do not exist in an in-process dispatcher. Teams that bolt them on with retry tables and polling loops usually end up with a worse broker.

Option Coupling visibility Flow readability Durability Replay, lag, backpressure
Direct call via module interface Explicit High Same transaction No
Orchestrating service or process manager Explicit Highest Persisted state No
In-process events with outbox Implicit Low At-least-once Limited
External message broker Implicit Low Broker-managed Yes

Events reduce coordination between module teams, and they make later extraction cheaper because the contract already exists. The costs are harder debugging, idempotent handlers and contract maintenance.

Illustrative estimate, with assumed inputs: ten contracts cost 5 days to set up. Maintaining them costs about 1.25 days per month. Each cross-team change made through a direct call costs about 1 day of coordination. At 3 such changes a month, the setup pays back in roughly 3 months. At 1 change a month, it never pays back.

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.
  • The dependency graph answers "what does this touch?" in seconds instead of a manual audit.

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.
  • You can size a change's blast radius before merging, avoiding surprise cross-team firefighting.
  • 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.