In January I wrote Microservices Are Killing Your Performance (And Here's the Math). It passed 26,000 views and collected 33 comments. In the P.S. I offered a follow-up on "Modular Monolith Architecture". This is it.
The most useful comments weren't defending microservices so much as attacking the thing I compared them with:
- Daniel Balcarek pointed out that in my setup the services shared one database, and that "each service should ideally have its own database => Database per Service pattern."
- A Makenzi wrote the harshest one, starting with "This is not a well-done article, I am sorry, I have to point it out." The list behind it was fair: I ignored database-per-service, I ignored events (Kafka, NATS, RabbitMQ), and I ignored the limits of a monolith.
- Adam - The Developer had the most-liked comment, and it was about bad boundaries, not network calls: "if you need to deploy in order, you're violating it." And: "You can't ship x number of distributed monoliths and call it micro-services."
- Scott asked directly for "a follow-up on modular monolith patterns".
Put those together and the real question is not "monolith or microservices". It's: how do you get the boundaries that microservices force on you, without paying for the network? That's what a modular monolith is.
In January I gave you four bullet points about it. This time I'll do what I did with Redis: use real code and real numbers. The code is LogTide's backend, the open-source observability platform I've been building for a bit over a year. I wrote a small script that measures how modular a modular monolith actually is, ran it on LogTide, and I'll show you everything it found, including the parts that aren't pretty.
What a modular monolith is, in one sentence
One deployable, split into modules that own their code and their data, and talk to each other only through a small public interface.
Each half of that sentence rules something out:
- "One deployable" rules out microservices. One build, one deploy, function calls instead of HTTP, one transaction when you need one.
- "Own their code and their data, talk only through an interface" rules out the classic big ball of mud. A
modules/folder is not enough. Folders are a suggestion. The question is whether anything stops you from ignoring them.
That second half is the part most people skip, and it's the part this post is about.
The specimen: LogTide's backend
LogTide is a TypeScript monorepo. These numbers are from commit 4c1e310 (25 November 2026):
-
One backend codebase, 45 modules under
packages/backend/src/modules:ingestion,query,alerts,sigma,siem,traces,auth,projectsand so on. About 74,000 lines, tests excluded. -
One Docker image, two processes.
server.tsstarts the API.worker.tsstarts 14 background workers (alerts, Sigma detection, webhooks, digests...). Indocker-compose.ymlboth services use the samelogtide/backendimage; the worker just runs withcommand: ["worker"]. - One PostgreSQL database (with TimescaleDB), application tables in one schema, 81 migrations.
-
One real package boundary: log storage lives in
@logtide/reservoir, a separate workspace package with three engines (TimescaleDB by default, ClickHouse and MongoDB as alternatives).
Split into microservices, even after merging the small modules, this would probably be a dozen services. It runs on Docker Compose, and I've written about why that's enough.
I measured my own boundaries
Saying "we have modules" is easy. So I wrote modmap.py (full source at the end): under 100 lines of Python, no dependencies. It treats every folder in modules/ as a module, follows the relative imports, and also checks which module reads and writes which table. Here's the output on LogTide (trimmed):
modules: 45
module-to-module dependencies: 188 (from 259 import statements)
through the target's index: 30 deep into internals: 229
pointing at platform modules ['audit-log', 'auth', 'organizations', 'projects', 'users']: 108
most depended-on: auth (38), audit-log (25), organizations (21), projects (13), users (11), notification-channels (7), settings (6), metering (5)
imported by nobody: capabilities, digests, invitations, onboarding, receivers, retention, sourcemaps, status-incidents, web-vitals
pairs that import each other: 15
tables seen: 75 used by >1 module: 34 written by >1 module: 13
projects: used by 26 modules
organization_members: used by 15 modules
Four things in there are worth your time, because you'll find the same four in your own codebase.
1. 188 dependencies that cost nothing
45 modules depend on each other in 188 places. Every one of them is a function call that takes nanoseconds, runs in the same transaction if it needs to, and shows up in one stack trace.
In a microservices version, every arrow that crosses a service boundary becomes an API contract: a client, a timeout, a retry policy, a version to keep compatible, and a failure mode. Even with a dozen services, a lot of these 188 arrows would cross one. That's the math from January seen from the other side. The point isn't only that a network call is slow. The point is that you pay for every dependency, and real systems have a lot of them.
2. Five modules everyone depends on, and that's fine
108 of the 188 dependencies point at just five modules: auth, audit-log, organizations, projects and users. auth alone is imported by 38 of the other 44 modules.
That isn't a design failure. Every feature in a multi-tenant app has to ask "who is this user, which organization, which project, and log that they did it". Those five modules are the platform, sometimes called the shared kernel. You can't remove that dependency. You can only make it explicit, keep the platform small and boring, and change it carefully.
It's also the clearest argument against splitting the platform into services. If auth and projects were services, 38 modules would depend on another service being up, or on a shared auth library that every service has to upgrade in lockstep.
3. 25 other modules use the projects table
The import graph shows you code coupling. The table check shows you data coupling, which is the one that hurts when you try to split.
projects shows up in 26 modules: its owner and 25 others. organization_members is used by 14 modules besides its owner. 13 tables are written by more than one module. In a monolith with one database, that's normal and it works: a foreign key and a JOIN are free.
But it tells you exactly what a split would cost. Daniel's "database per service" sounds clean until you count. Giving projects its own database means 25 modules lose their JOIN and replace it with an API call or a replicated copy of the data. That's not a refactor, that's a project.
4. Folders are a suggestion. Packages are a wall.
This is the one I find most interesting.
Of the 259 imports between modules, 30 go through the target's index.ts. The other 229 reach straight into a file inside the other module, like ../auth/middleware.js. Nothing in TypeScript stops that, and on a busy day the shortest import path wins.
Now look at @logtide/reservoir. The backend's code imports it in 27 places (tests excluded, like the module numbers above). All 27 go through the package entry, @logtide/reservoir. Not one reaches into its internals. The reason is mechanical: the package's exports field lists only the entry points, so a deep import doesn't even resolve. On top of that, the package has a conformance suite (15 test suites) that defines how every engine must behave and can be run against TimescaleDB, ClickHouse and MongoDB, so the interface is pinned down by tests, not by good intentions.
Same codebase, same people, two very different outcomes. The difference isn't discipline. It's whether the tooling enforces the boundary.
That's the core of this post: a modular monolith only stays modular if the boundaries are enforced by something other than willpower.
Making boundaries real
There are three levels of enforcement. Pick per module, not for the whole codebase.
Level 1: a lint rule
Cheapest to add, works on an existing codebase. I like dependency-cruiser for this, because it understands "same module" vs "other module" with a capture group:
// .dependency-cruiser.cjs
/** @type {import('dependency-cruiser').IConfiguration} */
module.exports = {
forbidden: [
{
name: 'module-internals',
comment: 'Use another module only through its index file',
severity: 'error',
from: { path: '(^|/)src/modules/([^/]+)/' },
to: {
path: '(^|/)src/modules/[^/]+/',
pathNot: ['(^|/)src/modules/$2/', '(^|/)src/modules/[^/]+/index\\.(ts|js)$'],
},
},
{
name: 'no-module-cycles',
severity: 'error',
from: { path: '(^|/)src/modules/' },
to: { circular: true },
},
],
options: {
tsConfig: { fileName: 'tsconfig.json' },
},
};
$2 is the module the import starts from (the second capture group, after the (^|/) that lets the same rule match src/modules/ whether you run it inside packages/backend or from the root of a monorepo). Imports inside your own module are fine, imports of another module's index file are fine, everything else fails. dependency-cruiser checks the file an import resolves to, so '../auth', '../auth/index.js' and '../auth/index.ts' all count as the public entry.
And no, one index.ts per module won't tank your backend build. The well-known problems with barrel files come from nesting them in every subfolder and re-exporting everything. One public entry point per module, exporting only what other modules need, is the opposite of that.
On an existing codebase this will light up. On LogTide's commit it reports 221 deep imports and 4 import cycles, the same from the monorepo root or from packages/backend. (It's a bit lower than modmap's 229, mostly because by default it skips type-only imports.) You don't fix 221 imports on a Monday. You freeze them:
npx depcruise-baseline src # writes .dependency-cruiser-known-violations.json
npx depcruise src --ignore-known # in CI: fails only on NEW violations
Now the number can only go down. Every time someone touches a file, they fix its imports, and the baseline shrinks. One practical note: dependency-cruiser reads TypeScript through the typescript package, and it supports specific versions. Run npx depcruise --info to check yours is on the list, otherwise it silently finds 0 modules.
Level 2: a workspace package
For a module with a stable, well-defined job, move it into its own package in the monorepo (pnpm, npm or Yarn workspaces) and list the public entry in exports:
{
"name": "@acme/billing",
"type": "module",
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }
}
}
Deep imports stop resolving. Dependencies between packages become visible in package.json, and pnpm warns you about cycles between workspace packages. This is what @logtide/reservoir is, and it's the reason it has a 27 out of 27 score.
It costs more: a build step, a package.json per module, and more friction when you change the interface. That friction is the point, but don't pay it for modules that are still changing shape every week.
Level 3: a separate process (same code, same image)
The last step before a service. You don't split the code, you split where it runs. LogTide's worker is exactly this: same image, different entry point. Alert notifications, Sigma detection and webhook deliveries can crash, retry or eat CPU without competing with the API for its event loop, and I didn't have to write a single API client to get that.
Data: one database, clear ownership
Database per module is where the January comments were most right and also most expensive. Here's the middle ground I'd recommend.
Every table has exactly one owner module, and only the owner writes to it. Other modules that need to change it call the owner's function. That gives you the most important property of "database per service" (one place that enforces the invariants of that data) without giving up transactions and foreign keys. On LogTide, modmap lists 13 tables with more than one writer. Several are pairs that also import each other, like incidents and siem, which usually means two modules want to be one.
Reads across modules are allowed, but explicitly. A JOIN across two modules' tables is one of the main reasons to have a monolith. Instead of banning it, put it in one place: a query module, a read model, or a view. Then "who depends on the shape of the projects table" has a short answer.
A schema per module is an option, not a requirement. CREATE SCHEMA billing; makes ownership visible in every query (billing.invoices), and you can give each module its own Postgres role to enforce it. But in one process with one connection pool, roles only help if each module gets its own pool. For most teams, a table-to-module map plus a check like modmap's "written by >1 module" in CI gets you most of the value. LogTide uses one schema.
Events go through the queue, not through each other. When incidents needs to react to something in alerts, it shouldn't import alerts' internals and it shouldn't be called synchronously in the middle of alerts' transaction. Enqueue a job. With a Postgres-backed queue like graphile-worker, the job can be inserted in the same transaction as the data change, so you get a transactional outbox without building one. (More on Postgres job queues here.) Fernando Fornieles said it well in the January comments: if one service must wait on another, they may belong in one service. Inside a monolith, the same rule tells you which calls should be direct and which should be jobs.
When to extract a real service
Philippe Santana Costa wrote in January that "Breaking up a monolith must be an empirical process." Agreed. These are the signals I'd look for. You want at least one of them, measured, not predicted:
- A different resource profile. One module needs 10x the CPU, a GPU, or a lot of memory, and scaling the whole app for it is wasteful.
- A different failure domain. When it breaks, it shouldn't take the rest down, and a separate process (level 3) isn't enough isolation.
- A different team and release cadence. A team that ships daily is blocked by a release train it doesn't control. This usually starts to matter around 50 engineers, not 5.
- Compliance. Data that legally has to live somewhere else, or be accessed by fewer people.
And before you extract, look at the module's fan-out. In LogTide, ingestion is the obvious candidate: it's the hot path, and it's where a higher, different load lands. But modmap says it depends on 7 other modules: auth, correlation, metering, pii-masking, projects, sigma and streaming. Extracting it today means 7 new contracts. The cheap move is level 3 first, a separate ingestion process from the same image, and only then a service if that isn't enough.
The path looks like this, and every step except the last is cheap to reverse:
The usual mistakes
-
A
sharedorcommonmodule that keeps growing. If something is used by everyone, it's either platform (make it a proper module with an owner) or a utility (make it boring and dependency-free). Acommonmodule that imports from feature modules is a cycle waiting to happen. -
Modules per entity instead of per capability.
users,orders,productsas modules turns every feature into a change in three modules.checkout,catalog,billingusually last longer. Your platform modules are the exception. - Transactions that span modules by accident. Passing a transaction object across a module boundary is sometimes right, but do it on purpose and keep the list short. If two modules are always in the same transaction, maybe they're one module.
-
Tests that reach into other modules. A test in
alertsthat inserts rows straight intoprojects' tables breaks every timeprojectschanges its schema. Use the owner's public functions or a fixture it provides. - "We'll enforce it later." Later, the baseline starts in the hundreds. Add the lint rule now, while the number is small.
TL;DR
- A modular monolith is one deployable whose modules own their code and their data and talk only through a public interface.
- I measured LogTide's backend: 45 modules, 188 dependencies between them. Split into services, a lot of those become API contracts.
- Five platform modules take 108 of those dependencies. That's normal. Keep the platform small and boring.
- Folders don't enforce anything: 229 of 259 cross-module imports skip
index.ts. The workspace package: 27 out of 27 through its entry. - Enforce with a lint rule plus a baseline, then packages, then separate processes. Extract a service only when you can measure why.
The script
Run it on your own modules folder (or features, domains, whatever you call it). The table check understands Kysely-style query builder calls; for another ORM, change the QB regex.
python3 modmap.py src/modules --platform auth,users
modmap.py (click to expand)
#!/usr/bin/env python3
"""modmap.py: how modular is your modular monolith?
Usage: python3 modmap.py <modules-dir> [--platform a,b,c]
Treats every direct subfolder of <modules-dir> as a module and reads its
.ts/.js files (tests excluded). Reports:
- module-to-module dependencies, and how many imports go through the
target's index file vs. deep into its internals
- fan-in (who is depended on) and modules that import each other
- tables touched by more than one module (Kysely-style calls such as
.selectFrom('t') / .insertInto('t'); plain SQL strings are counted only
for tables the query builder already revealed)
Only relative imports are followed. No dependencies, Python 3.8+.
"""
import os, re, sys, collections
args = sys.argv[1:]
if not args:
sys.exit(__doc__)
root = args[0]
platform = set()
if '--platform' in args:
platform = set(args[args.index('--platform') + 1].split(','))
mods = sorted(d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d)))
IMPORT = re.compile(r'''(?:from|import)\s*\(?\s*['"](\.[^'"]*)['"]''')
QB = re.compile(r'''\.(selectFrom|insertInto|updateTable|deleteFrom)\(\s*['"]([a-z_][a-z0-9_]*)''')
SQL_W = re.compile(r'''\b(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+([a-z_][a-z0-9_]*)\b''')
SQL_R = re.compile(r'''\b(?:FROM|JOIN)\s+([a-z_][a-z0-9_]*)\b''')
INDEX = {'index', 'index.js', 'index.ts'}
def sources(mod):
for dp, _, fs in os.walk(os.path.join(root, mod)):
for f in fs:
if f.endswith(('.ts', '.js')) and not re.search(r'\.(test|spec)\.', f) and not f.endswith('.d.ts'):
yield os.path.join(dp, f)
pairs = collections.Counter() # (from, to) -> import statements
deep = 0; via_index = 0
tables = collections.defaultdict(lambda: collections.defaultdict(set))
raw = []
for m in mods:
for path in sources(m):
src = open(path, encoding='utf-8', errors='replace').read()
for spec in IMPORT.findall(src):
rel = os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(path), spec)), root)
parts = rel.split(os.sep)
if parts[0] == m or parts[0] not in mods:
continue
pairs[(m, parts[0])] += 1
if len(parts) == 1 or (len(parts) == 2 and parts[1] in INDEX):
via_index += 1
else:
deep += 1
for op, t in QB.findall(src):
tables[t][m].add('read' if op == 'selectFrom' else 'write')
raw.append((m, src))
# plain SQL strings: only names already seen as tables via the query builder,
# so SQL keywords and CTE names don't get counted as tables
for m, src in raw:
for t in SQL_W.findall(src):
if t in tables:
tables[t][m].add('write')
for t in SQL_R.findall(src):
if t in tables:
tables[t][m].add('read')
edges = collections.defaultdict(set)
for (a, b) in pairs:
edges[a].add(b)
fan_in = collections.Counter(b for (a, b) in pairs)
mutual = sorted({tuple(sorted(p)) for p in pairs if (p[1], p[0]) in pairs})
stmts = sum(pairs.values())
print(f"modules: {len(mods)}")
print(f"module-to-module dependencies: {len(pairs)} (from {stmts} import statements)")
print(f" through the target's index: {via_index} deep into internals: {deep}")
if platform:
to_platform = sum(1 for (a, b) in pairs if b in platform)
print(f" pointing at platform modules {sorted(platform)}: {to_platform}")
print("most depended-on:", ", ".join(f"{m} ({n})" for m, n in fan_in.most_common(8)))
print("imported by nobody:", ", ".join(m for m in mods if fan_in[m] == 0) or "-")
print(f"pairs that import each other: {len(mutual)}")
for a, b in mutual:
print(f" {a} <-> {b}")
multi_r = {t: d for t, d in tables.items() if len(d) > 1}
multi_w = {t: sorted(m for m, ops in d.items() if 'write' in ops) for t, d in tables.items()}
multi_w = {t: ms for t, ms in multi_w.items() if len(ms) > 1}
print(f"tables seen: {len(tables)} used by >1 module: {len(multi_r)} written by >1 module: {len(multi_w)}")
for t, d in sorted(multi_r.items(), key=lambda x: -len(x[1]))[:5]:
print(f" {t}: used by {len(d)} modules")
for t, ms in sorted(multi_w.items(), key=lambda x: -len(x[1])):
print(f" {t} written by: {', '.join(ms)}")
If you run it, post your numbers in the comments. I'm curious how "through the index" vs "deep" looks in codebases much older than LogTide.
Does your monolith have real boundaries, or just folders? And what enforces them?




Top comments (0)