What is a modular monolith module API, and why are shared tables part of it?
A modular monolith module API is the full set of things other modules can couple to. Most teams count only the deliberate parts: exported functions and types, service interfaces, and the events a module publishes. In practice the API also includes every table, view and column that another module reads or writes directly. If the billing module runs a query against orders.status, then orders.status is part of the orders module's public contract, whether or not anyone wrote it down.
Coupling is defined by what breaks, not by what is documented. Suppose the orders team renames a column, splits a table, or changes what a status value means. Any module that queries that table directly will fail or, worse, silently misbehave. Calls into an exported function are visible in the code and get checked by the compiler or type checker. A raw SQL string in another module's repository layer usually gets neither, so the dependency stays hidden until a migration exposes it. An undocumented table that a second module queries is still public API. It is simply public API that nobody reviews or versions.
This matters most to backend and platform teams running several modules in one process against one database. In that setup the database imposes no boundary. Every module can reach every table, often through the same connection pool and credentials. The easy path is to join across module data directly, and each such join widens the module API without anyone choosing to.
+-------------------------- one process, one pool -------------------------+
| |
| +---------- orders module ----------+ +------ billing module ------+ |
| | exported functions / types |<---| calls (type-checked) | |
| | published events |--->| event handlers | |
| | | | | |
| | repository | | repository (raw SQL) | |
| +-----------------+-----------------+ +-------------+--------------+ |
| | | |
+--------------------+------------------------------------+----------------+
| owns | SELECT status
v | FROM orders
+--------------------- one database ----------------------+----------------+
| | |
| +----------- orders tables -----------+ | |
| | orders.id | | |
| | orders.status |<---------------+ |
| | orders.total | hidden dependency: |
| +-------------------------------------+ not type-checked, |
| not reviewed or versioned |
+--------------------------------------------------------------------------+
orders API = exported functions + events + orders.status (undeclared)
Billing couples to the orders module through two paths: the declared, type-checked function and event interface, and a raw SQL query on orders.status that the shared database permits. Because billing depends on that column, it is part of the orders module API, but nobody reviews or versions it.
How does an interface-based module API work?
An interface-based module API splits each module into a public surface and a private interior. The public surface is small and deliberate. It holds the interfaces or facade functions other modules may call, the DTO types those functions return, and the events the module publishes. The interior holds everything else: repositories, ORM entities, SQL, and the tables themselves. Other modules never see the interior.
At runtime a cross-module read follows these steps:
- The consumer calls the owner's interface. Billing needs an order's status, so it calls something like
OrderQueries.getStatus(orderId)instead of queryingorders.status. Billing depends on the interface type only. - The call is an ordinary in-process function call. Nothing is serialized and no network is involved. The cost matches any other method call, plus whatever query the owner runs.
- The owner translates the request into its own storage access. The orders module's implementation queries its own tables, which may mean a join, a cache lookup, or a different table after a refactor. It maps the result to a DTO.
- The consumer receives plain data. The DTO carries no lazy-loading hooks and no reference back to the database row, so the consumer has no path to write through it.
The wiring happens in one place, usually the application's composition root or dependency injection setup. There the concrete implementation of each module's interface is constructed and passed to the modules that need it. Consumers receive an interface. They never construct the owner's internals.
This arrangement moves the contract from the schema to the interface. When the orders team changes its tables, it updates its own implementation and keeps the interface signature stable. The type checker confirms that every caller still compiles. If the interface itself has to change, the compiler lists every call site. Writes follow the same pattern: the consumer calls a command on the owner's interface, such as Inventory.reserve(items), and the owner enforces its own invariants. Events cover the cases where the owner should tell others something happened without knowing who is listening.
The database can back this up. Per-module schemas and grants, covered below, make a direct query against a foreign table fail even when someone bypasses the interface in code.
Who should use interface-based module APIs instead of shared tables?
The approach pays off for teams where the cost of hidden schema coupling is already visible or soon will be:
- Several teams sharing one codebase and database. Once different teams own different modules, a column change by one team can break another team's code without warning. Interfaces let each team change its storage on its own schedule.
- Backend and platform teams responsible for long-lived systems. The longer a schema lives, the more readers it accumulates. An interface caps the set of readers at one: the owning module.
- Teams that may extract a module into a separate service later. A module that already exposes only an interface and events can be moved behind a network boundary without rewriting every consumer's queries. The extraction is still not free, as the transactions section explains.
- Teams with domains that carry strong invariants, such as balances, inventory counts and order totals, where a write from outside the owning module could leave data inconsistent.
It suits a small team or an early-stage codebase less well. If one team owns every table and the domain is still shifting week to week, the extra layer adds work to every change and isolates little. The migration section returns to this point.
When should you use interfaces, and when are shared tables acceptable?
Use interfaces for cross-module access when any of these is true:
- A schema change in one module has needed coordination with another module's owners, or a migration has broken code outside the module that ran it.
- You cannot list every reader of a table without searching query strings.
- The data has invariants that only the owning module should enforce.
- Two modules are owned by different teams with different release schedules.
- You expect to move a module to its own database or service at some point.
Shared table access is a reasonable choice in narrower cases:
- During a migration, as a temporary state while call sites are moved behind an interface.
- Analytics and reporting, which need wide joins across modules. Serve them from a read replica or a dedicated read model, and document that their dependencies on the schema may break.
- A single-team codebase, where the people who change the schema are the same people who read it.
- Stable reference data, such as country or currency lists, exposed through an owner-maintained view so the dependency is at least declared.
The deciding question is whether the owner can change its tables without asking anyone. If the answer is no and that is causing friction, move the access behind an interface. If the friction does not exist yet, a declared read through a view or a column-level grant may be enough for now.
Why do shared tables erode encapsulation faster than shared code?
Code coupling announces itself. If billing imports a class from orders and that class changes shape, the build fails, and the error names the file and line. SQL coupling gives no such signal. A dependency on customers.address_line1 can sit in a query string, an ORM relationship mapping, or a nightly reporting job owned by another team, and nothing ties those references to the schema until the query runs. A column rename surfaces as a runtime error. A change in meaning is worse. If country moves from a free-text name to a two-letter code, every query still executes and quietly returns wrong results.
Worked example (illustrative estimate)
Assume orders and billing both read a customers table. Billing has six queries that touch address columns, orders has four, and one reporting job joins all three modules' tables. Address storage moves from inline columns to a separate customer_addresses table so a customer can have several addresses.
| Step | Shared-table design | Interface design |
|---|---|---|
| Find consumers | Text search for column names across queries, ORM mappings and report SQL. Dynamic SQL is missed. | Compiler or IDE lists callers of the address lookup |
| Make the change | 11 edits across three owners' code | Customers module rewrites its own queries. The interface is unchanged. |
| Catch mistakes | Production errors or incorrect invoices | Customers module's contract tests |
| Release | Coordinated deploy, likely with a dual-write period | One module deploy |
Under these assumptions, the shared-table design spends most of its effort on discovery and coordination, not on the edit itself. The interface design limits the change to the module that owns the data.
How should you assign table ownership across module boundaries?
Start with three rules and apply them without exceptions.
- Every table has exactly one owning module. If no one can name the owner, the table is already shared. Assign it before you write any new code against it.
- Only the owner writes. Inserts, updates, deletes, and schema migrations all go through the owning module. This keeps invariants in one place. A rule such as "an order total equals the sum of its lines" stays true only when a single code path can change those rows.
- Reads by other modules are explicit decisions. Record each cross-module read in the owner's documentation or boundary configuration. Then the owner knows which columns it cannot freely rename. A read that nobody wrote down is a hidden dependency waiting to break.
Make ownership visible in the database
Put each module's tables in its own schema, such as billing.invoices and catalog.products. If your database lacks schemas, use a table prefix such as billing_invoices. Either way, a reviewer can see from a query alone that catalog code is joining into billing data. Schemas also let you grant write privileges per module role, which turns rule 2 into something the database enforces.
Draw the boundary carefully
None of these rules rescues a bad split. Suppose two modules constantly need each other's rows in the same transaction. Then the boundary is in the wrong place, and an API between them only formalizes the coupling. When entities change together, merging the two modules is often cheaper than building an interface for one module to call the other. Redraw the boundary early, while moving tables still costs little.
-- PostgreSQL: one schema per module makes ownership visible in every query.
-- One role per module lets the database enforce "only the owner writes".
CREATE ROLE billing_module NOLOGIN;
CREATE ROLE catalog_module NOLOGIN;
-- The owning role owns the schema, so only it runs migrations there.
CREATE SCHEMA billing AUTHORIZATION billing_module;
CREATE SCHEMA catalog AUTHORIZATION catalog_module;
CREATE TABLE catalog.products (
product_id bigint PRIMARY KEY,
name text NOT NULL,
list_price numeric(12,2) NOT NULL,
supplier_id bigint -- internal to catalog, not shared
);
ALTER TABLE catalog.products OWNER TO catalog_module;
CREATE TABLE billing.invoices (
invoice_id bigint PRIMARY KEY,
product_id bigint NOT NULL,
amount numeric(12,2) NOT NULL
);
ALTER TABLE billing.invoices OWNER TO billing_module;
-- Explicit cross-module read: billing may SELECT three named columns.
-- This grant is the record of the dependency. catalog now knows it
-- cannot rename these columns without coordinating with billing.
GRANT USAGE ON SCHEMA catalog TO billing_module;
GRANT SELECT (product_id, name, list_price)
ON catalog.products TO billing_module;
-- No INSERT/UPDATE/DELETE is granted to billing_module on catalog,
-- so a write from billing code fails with a permission error.
-- Inspect every cross-module read in one place:
SELECT grantee, table_schema, table_name, column_name, privilege_type
FROM information_schema.column_privileges
WHERE table_schema = 'catalog' AND grantee <> 'catalog_module';
PostgreSQL schemas and roles per module, where the owner role holds write and migration rights and another module's read access is a column-level SELECT grant that the database records and enforces.
What are the alternatives for cross-module data access?
Once a boundary is settled, the remaining question is how a consumer reads data it does not own. The four common options trade coupling against consistency and effort.
| Option | Coupling | Consistency | Main cost |
|---|---|---|---|
| Direct reads of owner's tables | Tightest | Immediate | Any owner schema change can break consumers |
| Owner-maintained read-only view | Tight | Immediate | Ties consumers to the owner's schema and database engine |
| In-process facade returning DTOs | Moderate | Immediate | Boilerplate; N+1 risk without batch methods |
| Domain events into local projections | Loosest | Eventual | Duplicated data, lag, replay tooling |
Direct reads suit only a short transition while you add one of the other three. Nothing marks which columns consumers depend on, so the owner cannot safely refactor.
A view is a cheap published contract. The owner can rename columns underneath as long as the view's shape holds. It still assumes both modules share a database and SQL dialect, so it blocks moving the owner to a separate store later.
A facade hides storage completely. It should return module-owned DTOs, not ORM entities. Entities leak lazy-loading behaviour and invite writes through the back door. Single-item lookups called inside loops become N+1 queries, so expose batch methods such as findCustomersByIds(ids).
Projections fit read-heavy consumers that need data in their own shape or that may be extracted later. Avoid them when the consumer cannot tolerate stale reads, such as checking a balance before a debit.
// customers module: public API. Consumers import only this file.
export interface CustomerSummary {
readonly id: string;
readonly displayName: string;
readonly tier: 'standard' | 'premium';
}
export interface CustomerQueries {
// Batch lookup so callers make one call per page of orders, not one per order.
findCustomersByIds(ids: readonly string[]): Promise<Map<string, CustomerSummary>>;
}
// Internal row type. It never leaves the module.
interface CustomerRow { id: string; first_name: string; last_name: string; tier_code: string; }
interface CustomerRepository { findByIds(ids: string[]): Promise<CustomerRow[]>; }
export class CustomerQueriesImpl implements CustomerQueries {
constructor(private readonly repo: CustomerRepository) {}
async findCustomersByIds(ids: readonly string[]): Promise<Map<string, CustomerSummary>> {
const unique = [...new Set(ids)];
if (unique.length === 0) return new Map();
// One query (e.g. WHERE id IN (...)) regardless of how many ids are passed.
const rows = await this.repo.findByIds(unique);
// Map to plain DTOs: no lazy loading, no way to write back through the result.
return new Map(rows.map((r): [string, CustomerSummary] => [r.id, {
id: r.id,
displayName: `${r.first_name} ${r.last_name}`,
tier: r.tier_code === 'P' ? 'premium' : 'standard',
}]));
}
}
// orders module: consumer. Collect ids first, then resolve them in one call.
export async function describeOrders(
orders: { id: string; customerId: string }[], customers: CustomerQueries,
) {
const byId = await customers.findCustomersByIds(orders.map(o => o.customerId));
return orders.map(o => ({ orderId: o.id, customer: byId.get(o.customerId)?.displayName ?? 'unknown' }));
}
A customers-module facade exposes a batch lookup that returns module-owned DTOs, and the orders module resolves all of its customer ids in a single call to avoid N+1 queries.
How do you keep transactions consistent without shared-table writes?
In a monolith, a module boundary is a code boundary, not a process boundary. That means the Orders module can call Inventory.reserve(items) through its public interface, and both writes can commit or roll back in one local database transaction. Orders never touches the inventory tables. It only calls the interface, which runs on the same connection and inside the same transaction scope. You get encapsulation and atomicity at once, which services cannot offer without significant machinery.
The cost is coupling to a shared transaction context. The interface has to accept or detect an ambient transaction, and it must not commit on its own. Make that rule explicit in the module API contract. Otherwise one module silently ends the caller's unit of work.
This guarantee disappears once a module must be deployed independently and owns its own database. Then the usual approach is the transactional outbox. Orders writes its own state and an "order placed" message to an outbox table in the same local transaction. A separate relay publishes that message. Inventory consumes it, ideally idempotently, because delivery is at-least-once. Consistency becomes eventual, and failed reservations need compensating actions instead of rollbacks.
A clean module API makes that extraction mechanical at the call sites, but not free. A synchronous in-process call becomes a network call. That call can time out, partially fail or add latency. You also have to choose between distributed transactions and sagas, and neither existed while everything shared one database.
import sqlite3
class InsufficientStock(Exception):
pass
class Inventory:
def reserve(self, conn: sqlite3.Connection, sku: str, qty: int) -> None:
cur = conn.execute(
"UPDATE inventory_stock SET available = available - ? "
"WHERE sku = ? AND available >= ?", (qty, sku, qty))
if cur.rowcount == 0:
raise InsufficientStock(sku) # caller decides to roll back
class Orders:
def __init__(self, inventory: Inventory):
self.inventory = inventory # depends on the interface, not on inventory tables
def place(self, conn: sqlite3.Connection, order_id: str, sku: str, qty: int) -> None:
with conn: # one local transaction: commit on success, rollback on exception
conn.execute("INSERT INTO orders_order (id, sku, qty) VALUES (?, ?, ?)",
(order_id, sku, qty))
self.inventory.reserve(conn, sku, qty)
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE inventory_stock (sku TEXT PRIMARY KEY, available INTEGER NOT NULL);
CREATE TABLE orders_order (id TEXT PRIMARY KEY, sku TEXT, qty INTEGER);
INSERT INTO inventory_stock VALUES ('SKU-123', 5);
""")
orders = Orders(Inventory())
orders.place(conn, "ord-1", "SKU-123", 3) # both writes commit together
try:
orders.place(conn, "ord-2", "SKU-123", 3) # not enough stock left
except InsufficientStock:
pass
print(conn.execute("SELECT COUNT(*) FROM orders_order").fetchone()[0])
The Orders module calls the Inventory module's public interface on a shared connection, so the order insert and the stock reservation commit or roll back as one local transaction without Orders ever touching inventory tables.
How can you enforce module boundaries mechanically?
Conventions decay under deadline pressure, so the boundary has to fail loudly when someone crosses it. There are four common layers of enforcement, and each covers a different path.
Language visibility. Package-private classes in Java, internal in C# or Kotlin, or unexported identifiers in Go keep a module's repositories and entities out of reach. This approach costs little, but it only protects code. It does nothing to stop a query string.
Architecture tests. A test in the normal suite can assert that nothing outside billing imports billing.persistence. The build then fails on the commit that introduces the dependency, which is when the change is cheapest to undo.
Per-module database roles or schemas. Each module connects with a role that has grants only on its own schema. This is the only layer that catches a raw query against a foreign table. It is also the most expensive. Migrations need an owner role. Connection pools multiply per module. Local setup and test fixtures must create every role and grant. If the tooling doesn't absorb that work, developers start using a superuser locally, and the grants quietly stop meaning anything.
Review checks on raw SQL. A lint step or a CODEOWNERS-style rule can flag SQL strings that reference tables owned by another module and route them to the owning team for review.
None of these layers covers reporting jobs, admin consoles or ad-hoc scripts that connect with broad credentials. Enforcement is only as good as its coverage, so list those bypasses explicitly. Either give each one a scoped role or accept it as a documented exception.
How do you migrate a monolith where every module reads every table?
Start with an inventory, not a redesign. Capture which code touches which tables, either from database query logs tagged by application component or from a static search for table names across the codebase. The output is a matrix of modules against tables. Most teams find that a small number of cross-module reads account for most of the coupling, and that tells you where to start.
Next, assign an owner to every table, even provisionally. A wrong owner can be reassigned later. A table with no owner keeps accumulating readers while you work on the rest.
Then wrap the hottest cross-module reads behind interface functions on the owning module. Do this one call site at a time so each change stays small and reviewable. Once a table has no foreign readers left, revoke the other modules' grants on it. Tighten permissions one module at a time, because each revocation shows you any access the inventory missed. Finding that out in staging is far cheaper than finding it after a big-bang cutover.
Joins and reporting need a separate decision. Transactional paths should go through module APIs, even if that means two calls instead of one join. Analytics is different: it needs wide joins across many modules. Give it a read replica or a dedicated read model with looser rules, and document that its schema dependencies can break without notice.
Some teams should not do this yet. A small team or an early-stage codebase whose domain is still shifting will pay for the indirection on every change and get little isolation in return. Revisit the decision when schema changes start forcing coordination across teams.
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 modular monolith module api, 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.