What are in-process domain events in a modular monolith?
A domain event is a record that something meaningful already happened inside a module. Examples are OrderPlaced, PaymentCaptured, or CustomerEmailChanged. Three properties define it:
- Past tense. The event states a fact. It does not make a request.
OrderPlacedcannot be rejected by a subscriber, while a command likePlaceOrdercan. - Immutable. Once raised, its fields never change. Handlers can read it safely without defensive copies.
- Owned by the publisher. The Ordering module decides what
OrderPlacedmeans and what it carries. Usually that is the order ID, the customer ID, a timestamp, and only the data subscribers can't reasonably look up themselves.
Keeping the payload small is deliberate. Every field becomes a promise the publishing module has to keep.
That is why event contracts belong in the module's public API surface, next to its public service interfaces, and not inside its internals. Subscribers compile against the contract type only. If Shipping depends on Ordering's internal Order entity, any refactor of that entity breaks Shipping. If Shipping depends only on a stable OrderPlaced contract, Ordering can restructure its persistence and domain model freely.
With in-process domain events, publisher and subscribers run in the same process and are wired through an event dispatcher. There is no broker, network hop, or serialization boundary. This suits backend and platform engineers running a single deployable split into bounded modules. You get module decoupling where each module reacts to facts instead of calling its peers directly. You avoid the operational cost of running messaging infrastructure. You also keep the option to extract a module later, because its integration points are already explicit.
// ordering/public/events.ts: part of Ordering's public API surface.
// Subscribers import only this file, never Ordering's internals.
export interface OrderPlaced {
readonly type: "OrderPlaced"; // past tense: a fact, not a request
readonly orderId: string;
readonly customerId: string;
readonly occurredAt: string; // ISO-8601 timestamp
}
// shared/dispatcher.ts: a minimal in-process dispatcher (no broker, no serialization)
type Handler<E> = (event: E) => Promise<void>;
export class EventDispatcher {
private handlers = new Map<string, Handler<any>[]>();
subscribe<E extends { type: string }>(type: E["type"], handler: Handler<E>): void {
const list = this.handlers.get(type) ?? [];
list.push(handler);
this.handlers.set(type, list);
}
async publish<E extends { type: string }>(event: E): Promise<void> {
// Freeze so no handler can mutate a fact another handler will read
const frozen = Object.freeze({ ...event });
for (const handler of this.handlers.get(event.type) ?? []) {
await handler(frozen);
}
}
}
// shipping/subscriptions.ts: Shipping depends on the contract, not Ordering's Order entity
export function registerShipping(dispatcher: EventDispatcher): void {
dispatcher.subscribe<OrderPlaced>("OrderPlaced", async (e) => {
// Shipping looks up whatever else it needs using the IDs in the event
console.log(`Preparing shipment for order ${e.orderId}`);
});
}
A minimal TypeScript sketch of an immutable, past-tense OrderPlaced contract exposed from Ordering's public API, dispatched in-process to a Shipping subscriber that depends only on that contract.
Who should use in-process domain events?
In-process events fit a specific situation. The pattern is a good match if most of the following are true for your team:
- You ship one deployable with one primary database, and you have already split, or want to split, the codebase into modules with clear ownership, such as Ordering, Billing, Shipping and Notifications.
- Command handlers are accumulating side effects that belong to other modules. A typical sign is a
placeOrdermethod that also creates invoices, reserves shipping slots, sends emails and updates reporting tables, and every new requirement edits that same method. - Several teams or sub-teams work in the same repository, and changes in one module keep forcing edits and reviews in another.
- You want the option to extract a module into a separate service later, but you don't need independent deployment, scaling or fault isolation today.
- You don't want to run messaging infrastructure yet. Nobody on the team wants to own a broker cluster for traffic that never leaves one process.
The pattern is a poor fit in a few cases. A small application with one or two modules gains little from the indirection, because a direct call is easier to read. Teams that already need modules to scale or deploy independently should go straight to cross-process messaging. Flows where the caller needs an immediate answer should use direct calls. The final section covers these cases in more detail.
How does it work, end to end?
At a high level, one command flows through five steps:
- A command arrives. A request handler loads an aggregate in the publishing module, for example an
Order, and calls a domain method such asplace(). - The aggregate records events. As it changes state, the aggregate appends immutable, past-tense events like
OrderPlacedto an internal list. It does not call any other module. - The unit of work collects and dispatches them at a defined point. Handlers registered as pre-commit run inside the open transaction. The transaction then commits. Handlers registered as post-commit run after the commit, either directly or through an outbox table written in the same transaction.
- The dispatcher routes each event by type. It looks up the handlers registered for that event type and calls them in the same process. Subscribers in other modules depend only on the event contract and fetch anything else they need by ID.
- Failures are handled according to the handler's phase. A pre-commit failure rolls the whole command back. A post-commit failure is logged and, with an outbox, retried later until it succeeds or is parked as dead.
The following sections cover each of these pieces in turn: the dispatcher, the choice of commit phase, the outbox, boundary enforcement and testing.
How does an in-process event dispatcher work?
The dispatcher at the core of this is small. It exposes one operation, publish(event), and keeps a registry that maps each event type to a list of handlers. When an event arrives, the dispatcher looks up its concrete type, then calls each registered handler in order on the same thread. It has no queue, serializer, or retry loop. A working version fits in a few dozen lines.
Handlers get into the registry in one of two ways. If you already use a DI container, you can resolve every implementation of a generic handler interface for the event type at dispatch time. Otherwise, you can wire handlers explicitly in a startup routine, with one line per subscription. Explicit wiring is more verbose, but it gives you a single file that shows which module listens to what. That file is useful when you review boundary changes.
Choosing when to publish matters more than the dispatcher itself. Don't fire events from setters or from deep inside aggregate methods. If you do, a handler can run while the aggregate is still half-updated, and it may call back into code that hasn't finished. Instead, have aggregates record events in an internal list as they change state. The command handler or unit of work collects those lists and dispatches them at a single, defined point in the command lifecycle. Ordering is then the order in which the events were recorded, and timing is fixed by where that point sits.
Because dispatch is synchronous, debugging needs no special tooling. A stack trace runs from the command, through publish, into the handler, and a debugger steps through it like any other method call.
type Handler<E> = (event: E) => void;
type EventType<E> = new (...args: any[]) => E;
class EventDispatcher {
private handlers = new Map<Function, Handler<any>[]>();
subscribe<E>(type: EventType<E>, handler: Handler<E>): void {
this.handlers.set(type, [...(this.handlers.get(type) ?? []), handler]);
}
// Route by concrete class, then call handlers in registration order on this stack.
publish(event: object): void {
for (const handle of this.handlers.get(event.constructor) ?? []) handle(event);
}
}
class OrderPlaced { constructor(readonly orderId: string) {} }
abstract class AggregateRoot {
private pending: object[] = [];
protected record(event: object): void { this.pending.push(event); } // record, never publish here
pullEvents(): object[] { const e = this.pending; this.pending = []; return e; }
}
class Order extends AggregateRoot {
status = "draft";
constructor(readonly id: string) { super(); }
place(): void { this.status = "placed"; this.record(new OrderPlaced(this.id)); }
}
// Startup wiring: one line per subscription, so it is easy to see who listens to what.
const dispatcher = new EventDispatcher();
dispatcher.subscribe(OrderPlaced, (e) => console.log(`billing: open invoice for ${e.orderId}`));
// Command handler: the single, defined point where recorded events are dispatched.
function placeOrder(order: Order, save: (o: Order) => void): void {
order.place();
save(order);
for (const event of order.pullEvents()) dispatcher.publish(event);
}
This is a minimal synchronous dispatcher that routes events by type. The aggregate records events while it changes state, and the command handler publishes them only after the state change is complete and saved.
Should event handlers run before or after the transaction commits?
That same synchronous call raises a question the publisher cannot answer for its subscribers: does this handler belong inside the open transaction or after it? Treat the answer as a per-handler decision recorded at registration, not a global dispatcher setting.
A pre-commit handler runs inside the publisher's transaction. If the Billing module creates an invoice row when OrderPlaced fires, both writes commit or roll back together. You get atomicity without extra machinery. The cost is coupled failure. A handler exception rolls back the order, and a slow handler holds the publisher's locks and connection for longer. This only works when every write lands in the same database.
A post-commit handler runs after the commit succeeds. The order is safe no matter what the handler does, so it suits emails, cache invalidation and calls to external APIs. The cost is durability. If the process crashes or is redeployed between the commit and the handler finishing, the side effect is lost and nothing records that it was skipped.
In code, register each handler with a phase, such as phase: BeforeCommit or phase: AfterCommit. The unit of work drains the first queue before calling commit and the second queue after it. Make the phase a required argument so that no one gets a default by accident.
| Pre-commit (in-transaction) | Post-commit | |
|---|---|---|
| Guarantee | Atomic with the publisher's writes | Publisher's commit is never affected |
| Handler failure | Rolls back the publisher | Logged; publisher unaffected |
| Crash mid-dispatch | Nothing committed; consistent | Side effect silently lost |
| Typical use | Same-database projections, invariants across modules | Notifications, cache eviction, external calls |
type Phase = "BeforeCommit" | "AfterCommit";
interface DomainEvent { type: string; payload: unknown }
interface Tx { commit(): Promise<void>; rollback(): Promise<void> }
// Pre-commit handlers receive the open transaction; post-commit handlers do not.
type Handler = (event: DomainEvent, tx?: Tx) => Promise<void>;
class EventBus {
private subs: { type: string; phase: Phase; fn: Handler }[] = [];
// Phase is a required argument: every handler author must choose one.
subscribe(type: string, phase: Phase, fn: Handler) { this.subs.push({ type, phase, fn }); }
handlersFor(type: string, phase: Phase) {
return this.subs.filter(s => s.type === type && s.phase === phase).map(s => s.fn);
}
}
class UnitOfWork {
private pending: DomainEvent[] = [];
constructor(private tx: Tx, private bus: EventBus) {}
record(event: DomainEvent) { this.pending.push(event); }
async complete() {
try {
// Phase 1: same transaction. A throw here rolls back the publisher's writes too.
for (const e of this.pending)
for (const h of this.bus.handlersFor(e.type, "BeforeCommit")) await h(e, this.tx);
await this.tx.commit();
} catch (err) {
await this.tx.rollback();
throw err;
}
// Phase 2: publisher is already durable. Failures are logged, never propagated.
// A crash or redeploy at this point loses these side effects without a trace.
for (const e of this.pending)
for (const h of this.bus.handlersFor(e.type, "AfterCommit")) {
try { await h(e); } catch (err) { console.error(`post-commit ${e.type} failed`, err); }
}
}
}
// bus.subscribe("OrderPlaced", "BeforeCommit", createInvoiceRow);
// bus.subscribe("OrderPlaced", "AfterCommit", sendConfirmationEmail);
A unit of work that requires a dispatch phase on every subscription. It runs BeforeCommit handlers inside the transaction, where they can roll it back, and AfterCommit handlers once the commit succeeds, where failures are only logged.
How do you make post-commit events reliable with an in-process outbox?
The post-commit column's weak spot is the last row: a crash between commit and dispatch loses the side effect. The fix is to make the event part of the commit itself. Instead of dispatching directly, the command handler inserts each event into an outbox table in the same transaction as the state change. Either both rows land or neither does.
command ──► [ BEGIN
UPDATE orders ...
INSERT outbox (event_id, type, payload)
COMMIT ]
│
background worker (same process)
poll ─► claim batch ─► dispatch ─► handlers
│ │
└──── mark processed ◄─────┘
A worker thread in the monolith polls for unprocessed rows, dispatches them through the same event dispatcher, and marks them done. If the process dies mid-batch, the rows are still pending on restart. The result is at-least-once delivery with no broker.
Decisions you own
- Polling interval. A short interval reduces latency but adds idle queries. Many teams also nudge the worker in-process right after commit and keep polling as the fallback.
- Cleanup. Delete or archive processed rows on a schedule. Otherwise the table grows and the polling query slows down.
- Retries. Store an attempt count and a next-attempt timestamp, and use exponential backoff so that a failing handler does not spin.
- Poison events. After N attempts, move the event to a dead-letter state and raise an alert. A poison event should not block the queue.
Idempotency is mandatory
A crash after a handler succeeds but before the row is marked processed means that handler will run again. Handlers must tolerate duplicates. There are three common ways to do this:
- Record processed event IDs in a dedupe table, written in the handler's own transaction.
- Use upserts in place of inserts.
- Key writes on natural keys such as order ID, so that a repeated write is a no-op.
Ordering is not guaranteed by default, because retries and concurrent workers reorder events. You can get per-aggregate ordering by processing events serially per aggregate ID, but that limits parallelism and lets one stuck aggregate stall its successors.
-- PostgreSQL. Outbox row is inserted in the same transaction as the state change.
CREATE TABLE outbox (
event_id uuid PRIMARY KEY,
type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending', -- pending | processed | dead
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
created_at timestamptz NOT NULL DEFAULT now()
);
-- Partial index keeps the polling query cheap as processed rows accumulate.
CREATE INDEX outbox_due ON outbox (next_attempt_at) WHERE status = 'pending';
-- Worker: claim a batch of due events. SKIP LOCKED lets several workers run without contention.
SELECT event_id, type, payload FROM outbox
WHERE status = 'pending' AND next_attempt_at <= now()
ORDER BY created_at LIMIT 50
FOR UPDATE SKIP LOCKED;
-- On success:
UPDATE outbox SET status = 'processed' WHERE event_id = $1;
-- On failure: exponential backoff capped at 1h; after 10 attempts park it as dead (alert on this).
UPDATE outbox SET
attempts = attempts + 1,
next_attempt_at = now() + LEAST(interval '1 second' * power(2, attempts), interval '1 hour'),
status = CASE WHEN attempts + 1 >= 10 THEN 'dead' ELSE 'pending' END
WHERE event_id = $1;
-- Cleanup job: drop old processed rows so the table stays small.
DELETE FROM outbox WHERE status = 'processed' AND created_at < now() - interval '7 days';
-- Handler-side dedupe, run inside the handler's own transaction.
-- Zero rows inserted means this handler already saw the event: skip the side effect.
CREATE TABLE processed_events (handler text, event_id uuid, PRIMARY KEY (handler, event_id));
INSERT INTO processed_events (handler, event_id) VALUES ('send_receipt', $1)
ON CONFLICT DO NOTHING;
A PostgreSQL outbox table with batch claiming, exponential-backoff retries, a dead-letter state, scheduled cleanup, and a per-handler dedupe table that makes at-least-once delivery safe.
How do you enforce module boundaries, errors and observability?
Boundaries erode quietly in a monolith because nothing stops one module from importing another's internals. Make the rule explicit: a module may depend only on another module's public contract and its published event types. Enforce it with architecture tests in CI or with build-level dependency checks between separately declared modules, so a violation fails the build instead of relying on code review. Keep each module's tables private too. If Billing needs a customer's country, the CustomerRegistered event carries it and Billing stores its own copy. A cross-module join would recouple the schemas the events were meant to separate.
Decide failure semantics once, in the dispatcher. For post-commit handlers, isolate failures: record and retry the one that threw, and let its siblings run, because they share nothing except the trigger.
Every log line and span emitted during dispatch should carry the event ID and the originating request's correlation ID, so a single search reconstructs the whole fan-out. Export outbox lag (the age of the oldest unprocessed row) and failed-event counts as alerting metrics. Rising lag is usually the first sign of a stuck handler.
Watch for chains. When a handler publishes events that trigger further handlers, control flow becomes invisible, cycles become possible, and pre-commit chains stretch one transaction across several modules. Cap chain depth or flag chains in review.
Keep events thin. Include the facts consumers need, not entity snapshots that leak internal state. Treat widely consumed events as APIs: only add optional fields, and publish a new versioned event type for breaking changes.
How should you test in-process domain events?
Test at three levels. Each one catches a different class of bug.
Aggregates: assert on raised events
Domain logic should be testable without a dispatcher. Call a method on the aggregate, then inspect the events it collected. Assert on the event type and on the facts the event carries. Also assert that failed invariants raise nothing. This keeps the event a deliberate part of the aggregate's behaviour rather than a side effect hidden in infrastructure.
Handlers: test in isolation
Construct the handler with fakes for its dependencies and pass it a hand-built event. You are checking that it reacts correctly to the contract, not to whatever the publishing module happens to send today. Include a test that delivers the same event twice and asserts the outcome is unchanged.
End to end: commit, outbox, dispatch
Run one integration test against a real database. Execute a command, commit, and verify the outbox row exists before any handler has run. Then simulate a crash: stop the process, or skip dispatch, after the commit. Start a fresh dispatcher and confirm it picks up the pending row and the handler's effect appears. Finally, mark the row unprocessed and dispatch again to prove idempotency holds against real persistence, not just fakes.
Why this is worth it
Ordering and timing bugs rarely show up on a developer machine. Examples include a handler reading uncommitted state, an event lost on restart, or a double-applied side effect. They appear under real load and crashes, where they are slow to reproduce and diagnose. Forcing those conditions deterministically in a test turns a long production investigation into a failing build.
How can in-process events save engineering time?
The time savings come from changing where work happens when requirements change, not from making any single request faster. They show up in five places.
New reactions don't touch the publisher. Without events, adding "send an SMS when an order is placed" means editing Ordering's command handler, adding a dependency on a Notifications service, and getting a review from Ordering's owners. With events, the Notifications team adds one handler and one subscription line in their own module. The publisher's code, tests and reviewers are not involved. The same applies when a reaction is removed.
Fewer cross-team merge conflicts and review hops. When side effects live in their owning modules, the central command handler stops being the file every team edits. Each change is reviewed by the team that owns the affected code.
No messaging infrastructure to run. There is no broker to provision, secure, upgrade, monitor or reproduce in local development and CI. A new engineer runs one process and one database. Integration tests need no container for a broker.
Faster debugging of synchronous paths. A failure in a handler produces one stack trace from the command to the handler, which a debugger can step through. Cross-process messaging spreads the same investigation across separate logs and processes, and correlation IDs are required to stitch it back together.
Cheaper extraction later. Because integration points are already explicit, serializable contracts recorded in an outbox, extracting a module is mostly a change of transport. Without events, it starts with finding every direct call into the module.
The savings are not free. Someone has to build and maintain the dispatcher, the outbox and the idempotency checks, and indirection makes "what happens when an order is placed?" harder to answer by reading one method. The explicit wiring file and correlation-ID logging described earlier reduce, but do not remove, that cost.
As an illustrative estimate, using entirely assumed inputs rather than measured results: assume a team adds 4 new side effects per month to existing commands. Assume each one, done as a direct call in the publisher's code, needs an extra review round with another team that adds 1 day of elapsed time and 1 hour of reviewer effort. Then the event-based approach avoids roughly 4 days of waiting and 4 reviewer-hours per month. Against that, assume a one-off cost of a few days to build the dispatcher and outbox, plus occasional maintenance. Substitute your own numbers. If your team rarely adds cross-module reactions, the balance can easily go the other way.
When should you avoid in-process events, and what are the alternatives?
Events are the wrong tool when the caller needs an answer. If checkout must know whether inventory reserved stock before confirming an order, publishing an event and waiting for a reply hides a synchronous dependency behind async plumbing. Call the inventory module's public interface directly instead. Events also cannot help when modules need independent scaling or deployment cadences, or when you need fault isolation. One process and one database mean a memory leak in reporting or a bad deploy of billing takes every module down together.
| Approach | Coupling | Delivery guarantee | Operational cost | Development cost |
|---|---|---|---|---|
| Direct module API call | Compile-time, synchronous | Same transaction | None extra | Lowest |
| In-process events | Contract only, same process | Lost on crash after commit | None extra | Low |
| In-process events + outbox | Contract only, same process | At-least-once | Relay job, outbox table | Moderate |
| External message broker | Contract only, cross-process | At-least-once (needs outbox to avoid dual writes) | Broker cluster to run | Moderate–high |
| Separate services | Network contract | Per integration | Highest | Highest |
The in-process approach is not free. You own the dispatcher, the outbox table, the relay, retries and idempotency checks, and you maintain them like any other infrastructure code. What you get back is no broker to provision, monitor or upgrade, a local environment that is one process plus one database, and stack traces that cross module boundaries in a single debugger session.
The design also leaves room to grow. Events are already serializable contracts, and the outbox already records them durably. To extract a module, you mostly point the relay at a broker instead of the in-process dispatcher, then move the consuming module's handlers behind a broker subscription.
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.