Cross-module calls, in-process events and transactions
Choose between a direct call and an in-process event for each cross-module interaction, see what happens to the main flow and to the reaction when a handler fails inside the transaction, after commit, or through an outbox, and keep the seams that make a later extraction cheap.
Contentsand lesson path
On this page
- Why it matters
- Direct calls and in-process events
- Work that spans modules: three timings
- Seams for a later extraction
- Check your understanding
- Apply it
- Review prompt
Lessons of Modular Monolith
- Why modular first: cost of distribution versus cost of coupling Concept · 15 min
- Module anatomy, owned tables and component principles Concept · 25 min
- Enforcing boundaries with architecture tests Lab · 25 min
- Cross-module calls, in-process events and transactions Concept · 20 min
- Carving a big ball of mud into modules Worked example · 30 min
- Modularity check Knowledge check · 6 questions
What you will learn
- Choose between direct calls and in-process events for cross-module communication and plan the seams that allow later extraction.
01. Why it matters
When a Spokes rider ends a ride, several modules care. Fleet must confirm that the dock accepted the bike before rentals can close the ride. Billing must charge the ride, and a lost charge is lost money. Notify sends a receipt; a late receipt is fine, a lost one becomes a support ticket. A loyalty module adds points, and nobody minds if that lags a minute.
These needs differ, so each interaction between modules has to pick two things: a style, either a direct call or an event, and a timing, either inside the same database transaction, after it, or through a stored record that survives a crash. Lesson 3 built the small event bus that Spokes uses; this lesson decides when to use it, what each timing does when a handler fails, and which seams keep a later extraction cheap.
02. Direct calls and in-process events
A direct call goes through the other module's public API: fleet.api.dock_bike(bike_id) returns an answer or raises an error. The caller depends on the callee, waits for it and handles its failure on the spot, so the flow is easy to read and to debug. Use a call when the caller needs the answer to continue, or when a failure must stop the operation: rentals cannot close a ride if the dock did not take the bike.
An event states a fact that has already happened, named in the past tense: RideEnded(ride_id, rider_id, minutes). The publisher does not know who listens; listeners depend on the publisher's event type, not the other way round. Adding loyalty points later means adding a subscriber, with no change to rentals. That inversion also serves the stable dependencies principle: a stable module can announce facts without depending on the volatile modules that react to them. Use an event for reactions the publisher neither waits for nor has to approve.
Inside one process an event needs no broker. The bus from lesson 3 is a dictionary from event type to a list of handlers, plus a loop that calls them, and that is enough until a module leaves the process. Kamil Grzybek's comparison of integration styles sums up the trade-off: a call is simpler and gives the freshest data but ties caller to callee, while messaging gives the loosest coupling at the price of more machinery and eventual consistency, and he recommends mixing both.
Two cautions. Events decouple code, not time: the lesson 3 bus calls every handler inside publish, so a slow or failing handler slows or fails the publisher unless you change when handlers run. And events can hide coupling: if one handler reads data that another handler writes, their order suddenly matters, and nothing in the code says so.
03. Work that spans modules: three timings
Suppose billing's tariff lookup times out once. What happens to the ride depends on when billing's handler runs. The script tries three timings with SQLite, which ships with Python; table-name prefixes stand in for the schemas of lesson 2.
"""events_demo.py: three ways for Billing to react when Rentals ends a ride.
Every scenario starts from a fresh in-memory SQLite database. Table prefixes
stand in for the rentals and billing schemas. Billing's handler fails on its
first call, like a tariff lookup that times out once.
"""
import json
import sqlite3
def fresh_db():
db = sqlite3.connect(":memory:", isolation_level=None) # we write BEGIN/COMMIT
db.executescript("""
CREATE TABLE rentals_rides (id INTEGER PRIMARY KEY, minutes INT, status TEXT);
CREATE TABLE billing_charges (ride_id INTEGER PRIMARY KEY, cents INT);
CREATE TABLE outbox (id INTEGER PRIMARY KEY, listener TEXT, payload TEXT,
done INT NOT NULL DEFAULT 0);
INSERT INTO rentals_rides VALUES (1, NULL, 'active');
""")
return db
class Billing:
def __init__(self):
self.calls = 0
def on_ride_ended(self, db, event):
self.calls += 1
if self.calls == 1:
raise TimeoutError("tariff lookup timed out")
db.execute("INSERT OR IGNORE INTO billing_charges VALUES (?, ?)",
(event["ride_id"], 100 + 25 * event["minutes"]))
def end_ride(db, minutes): # Rentals' own change
db.execute("UPDATE rentals_rides SET minutes = ?, status = 'ended' WHERE id = 1",
(minutes,))
return {"ride_id": 1, "minutes": minutes}
def report(db, label):
status = db.execute("SELECT status FROM rentals_rides").fetchone()[0]
charges = db.execute("SELECT count(*) FROM billing_charges").fetchone()[0]
pending = db.execute("SELECT count(*) FROM outbox WHERE done = 0").fetchone()[0]
print(f" {label}: ride {status}, charges {charges}, pending outbox rows {pending}")
def inside_transaction(db, billing):
try:
db.execute("BEGIN")
event = end_ride(db, 12)
billing.on_ride_ended(db, event) # same transaction as the ride update
db.execute("COMMIT")
except TimeoutError as err:
db.execute("ROLLBACK")
print(f" billing failed: {err}")
report(db, "afterwards")
def after_commit(db, billing):
db.execute("BEGIN")
event = end_ride(db, 12)
db.execute("COMMIT")
try:
billing.on_ride_ended(db, event) # runs only after the commit
except TimeoutError as err:
print(f" billing failed: {err}")
report(db, "afterwards")
def relay(db, billing):
for row_id, payload in db.execute(
"SELECT id, payload FROM outbox WHERE done = 0 ORDER BY id").fetchall():
try:
db.execute("BEGIN")
billing.on_ride_ended(db, json.loads(payload))
db.execute("UPDATE outbox SET done = 1 WHERE id = ?", (row_id,))
db.execute("COMMIT") # the charge and the 'done' mark commit together
except TimeoutError as err:
db.execute("ROLLBACK")
print(f" relay: billing failed ({err}), row {row_id} stays pending")
def with_outbox(db, billing):
db.execute("BEGIN")
event = end_ride(db, 12)
db.execute("INSERT INTO outbox (listener, payload) VALUES ('billing', ?)",
(json.dumps(event),))
db.execute("COMMIT") # ride update and outbox row: one local transaction
report(db, "after commit")
for run in (1, 2):
relay(db, billing)
report(db, f"after relay run {run}")
for title, scenario in [
("1) handler inside the rentals transaction", inside_transaction),
("2) handler after commit, no outbox", after_commit),
("3) outbox row in the rentals transaction, relay later", with_outbox),
]:
print(title)
scenario(fresh_db(), Billing())python3 events_demo.py1) handler inside the rentals transaction
billing failed: tariff lookup timed out
afterwards: ride active, charges 0, pending outbox rows 0
2) handler after commit, no outbox
billing failed: tariff lookup timed out
afterwards: ride ended, charges 0, pending outbox rows 0
3) outbox row in the rentals transaction, relay later
after commit: ride ended, charges 0, pending outbox rows 1
relay: billing failed (tariff lookup timed out), row 1 stays pending
after relay run 1: ride ended, charges 0, pending outbox rows 1
after relay run 2: ride ended, charges 1, pending outbox rows 01. Inside the publisher's transaction. The ride update and the charge commit together or not at all, the simplest consistency you can get. The price is in the first block: one failing secondary step rolled back the primary one, so the rider could not end the ride because a tariff lookup failed. Spring Modulith's documentation describes this as the behaviour of synchronous events: both changes succeed or neither does, and every listener widens the transaction.
2. After commit, with nothing stored. The ride ends whatever billing does, but the charge is simply gone and nothing remembers that it is owed. A process crash between the commit and the handler loses it in the same way. Spring Modulith warns about exactly this risk for listeners that run after commit.
3. After commit, through an outbox. Rentals writes the ride update and an outbox row, a record that billing still has to react, in one local transaction. A relay delivers pending rows and marks them done; a failure leaves the row pending for the next run. Spring Modulith's event publication registry does the same in production: one entry per listener, written in the original transaction and completed when the listener succeeds. Enqueue after commit with an outbox table covers relays in more depth.
Delivery through an outbox is at least once: a relay that dies after billing's work but before marking the row will deliver the event again. Here that cannot happen, because billing's charge and the done mark commit in one transaction of one database. If billing moves to its own database, that atomicity ends and the handler must recognise repeats itself; the INSERT OR IGNORE keyed by ride_id is already a second guard.
Which timing, then? Keep one local transaction only for a rule that must hold at every instant across both modules, such as debits and credits that must balance, and then ask whether the two are really one module, because a transaction that spans modules is the hardest thing to extract. Use the outbox for reactions that may lag but must not be lost, such as charges and receipts. Plain after-commit handlers suit work that is cheap to lose or easy to rebuild, such as refreshing a cache.
04. Seams for a later extraction
Michael Feathers defined a seam, as Martin Fowler quotes him, as "a place where you can alter behavior in your program without editing in that place"; the place where you choose the behaviour is the enabling point. For a module you might extract one day, keep four seams:
- Callers depend on an interface of the module's API, and one place, the composition root, chooses the implementation.
- The API takes and returns plain data and ids, not ORM objects or open sessions.
- Events leave through the outbox with an explicit payload, so the relay could later publish them to a broker instead of calling handlers.
- The module owns its tables, and no transaction spans it and another module.
The sketch shows the first two for a payments module, plus one cheap habit: an idempotency key, which makes a repeated request return the first result instead of charging twice.
"""seam.py: callers depend on a Protocol; one place picks the implementation."""
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class ChargeResult: # plain data, so it can cross a network later unchanged
charge_id: str
cents: int
class Payments(Protocol): # the seam: billing's callers see only this
def charge(self, rider_id: str, cents: int, key: str) -> ChargeResult: ...
class InProcessPayments: # today: an ordinary function call in the monolith
def __init__(self) -> None:
self._by_key: dict[str, ChargeResult] = {}
def charge(self, rider_id: str, cents: int, key: str) -> ChargeResult:
if key not in self._by_key: # same key, same result: no second charge
self._by_key[key] = ChargeResult(f"ch-{len(self._by_key) + 1}", cents)
return self._by_key[key]
def bill_ride(payments: Payments, ride_id: int, rider_id: str, cents: int) -> str:
result = payments.charge(rider_id, cents, key=f"ride-{ride_id}")
return f"ride {ride_id}: {result.charge_id} for {result.cents} cents"
# The enabling point: the only line to change when Payments becomes a service.
payments: Payments = InProcessPayments()
print(bill_ride(payments, 7, "r1", 400))
print(bill_ride(payments, 7, "r1", 400)) # a repeat with the same key
print(bill_ride(payments, 8, "r1", 250))python3 seam.pyride 7: ch-1 for 400 cents
ride 7: ch-1 for 400 cents
ride 8: ch-2 for 250 centsToday InProcessPayments is a method call that cannot get lost on the way. If payments becomes a service, the enabling point gets an HTTP client with the same charge signature and the callers do not change. What does change is the failure model: a call can time out without telling you whether the charge happened, which is exactly when the key protects you, and the price of distribution lists the rest.
Do not build the broker, the HTTP client or service discovery now. Keep the seams cheap, and let a real signal from lesson 1 decide whether you ever cross them; many modules never need to. Over-engineering the other way is also possible: an outbox for a cache refresh, or an interface for a module nobody will extract, is code that someone must still maintain.
05. Check your understanding
06. Apply it
Use the sample monolith of the practice task.
- List every interaction between its modules. For each one, choose a call or an event and a timing (inside the transaction, after commit, or outbox), and write one sentence on what happens when the other side fails.
- Mark every place where one transaction spans two modules, and decide whether the rule needs it or whether the two modules should be one.
- Pick the module you are most likely to extract. Write its interface with plain data types and the single line in the composition root that chooses the implementation.
07. Review prompt
Without looking back, explain when a direct call fits better than an event, and why an event reverses the dependency between two modules. Describe what happens to the main flow and to the reaction when a handler fails inside the transaction, after commit, and through an outbox, and why outbox delivery is at least once. Name four seams that keep a module extractable, and what changes, and what does not, on the day it becomes a service.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.