How-to › Run message-based services

How to split a monolith along API resource boundaries#

Read the first service seams off an OpenAPI document, then check each against the import graph and the tables each query touches, and cut where all three agree.

Audience
API producer
Level
advanced
Topic
Choose a service architecture
Languages
TypeScript
Verified

Your OpenAPI document gives /orders a path prefix and a tag of its own, so the order handlers look like the obvious first service. In the code, loading one order joins five tables, three of them owned by users and products, and creating one leans on foreign keys into both. Move orders into a database of its own, and every one of those statements stops working.

What you get

You will end up with a script that lays the spec’s resources, the import graph, and the tables each query touches over your bounded contexts, and cuts only where all three agree. This is for you if a monolith has an OpenAPI document and nobody agrees where the first service starts.

Short answer

Extract the resources from the OpenAPI document with @voxgig/apidef and read the import graph of the handler modules with dependency-cruiser. List every query that touches tables of more than one resource through SQLite’s EXPLAIN. Lay all three over the bounded contexts from event storming, and cut a context only where the spec, the code, and the data agree. In the sample shop, only Publishing passes.

You will need

Node 22.13 or later, the monolith’s OpenAPI 3 document, its handler modules, and its database schema. The sample is a shop with 16 operations, six handler modules, and seven tables in monolith/shop.db. It reads the file with node:sqlite, which needs no flag from Node 22.13 and prints an experimental warning on stderr. Run npm ci in the sample directory first.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
apidef entity extractionYou want resources named from paths and schemas, with parent keys, in a file you can diffA heuristic per release: the same document can classify differently on the next versionYour tags were designed as service names and are kept that way
dependency-cruiser import graphThe handlers live in modules whose imports are static and resolvableSees imports only, so two modules sharing a table look independentCoupling runs through the database rather than through code
Event storming into bounded contextsSeveral teams own the domain and the seam must match who owns whatA workshop with domain experts, and an outcome no tool can check against the codeNobody who knows the business is available for a day
Kiota request buildersYou generate clients with Kiota and want one client per seam from one documentFollows the path tree, so a nested resource keeps its parent’s builders in every callYour seams cut across path prefixes
OpenAPI tags and paths read by handA small document whose tags were written with careTags drift from paths, and nobody sees a disagreement until a cut breaksThe document has more operations than a reviewer holds in mind
Swagger Codegen tag classesYou generate clients with Swagger Codegen and your tags are the intended service namesOne API class per tag, so a stray tag becomes a class of its ownYour tags group by audience or by team rather than by resource

Voxgig maintains apidef, the extractor behind sdkgen. It is one of six readings on this page. Voxgig makes no other tool or method in the table.

No single row finds a seam. The spec readings are stable and visible to clients, but they cannot see a join. The import graph sees code and misses the database. Event storming matches the seams to the teams,1 and leaves you to prove that the code agrees.

Read the document three ways

resources.mjs reads every operation by its first tag, by its first path segment, and by the entity @voxgig/apidef 8.32.4 puts it on. That is the release @voxgig/create-sdkgen 0.31.9 installs, pinned here in the lockfile.

node resources.mjs
operation                                       tag       prefix    apidef 8.32.4
GET    /orders                                  Orders    orders    order.list
POST   /orders                                  Orders    orders    order.create
GET    /orders/{orderId}                        Orders    orders    order.load
GET    /products                                Catalog   products  product.list
GET    /products/{productId}                    Catalog   products  product.load
DELETE /user/{id}                               Admin     user      user.remove
GET    /user/{id}                               Accounts  user      user.load
GET    /users                                   Users     users     user.list
POST   /users                                   Users     users     user.create
GET    /users/{userId}                          Users     users     user.load
PUT    /users/{userId}                          Users     users     user.update
GET    /users/{userId}/posts                    Posts     users     post.list
POST   /users/{userId}/posts                    Posts     users     post.create
GET    /users/{userId}/posts/{postId}           Posts     users     post.load
GET    /users/{userId}/posts/{postId}/comments  Comments  users     comment.list
POST   /users/{userId}/posts/{postId}/comments  Comments  users     comment.create

groups: 7 tags, 4 prefixes, 5 entities
  comment  parent keys: post_id, user_id
  order    parent keys: none
  post     parent keys: user_id
  product  parent keys: none
  user     parent keys: none
warning: Points GET /user/{id} and GET /users/{userId} on entity=user op=load have the same selector (exist: id), so only GET /user/{id} is ever chosen. An action or another entity in guide.aontu tells them apart.

Three readings, three answers: seven tag groups, four path prefixes, five entities. The legacy /user/{id} paths carry the tags Accounts and Admin, so a tag reading invents two resources. On this document both apidef releases put those operations on user.

The parent keys matter for the cut. Every post and comment URL carries user_id, so the clients of a Publishing service still address it through /users/{userId}. That is a routing rule at the gateway, not a join.

The warning matters more than the counts. On 8.32.4 a plain load reaches only the legacy GET /user/{id}, so the canonical GET /users/{userId} is never chosen. legacy-load-guide.aontu gives the legacy path an action of its own, and the test shows 8.32.4 then choosing /users/{userId} for a plain load, with no warning.

generate.sh records the same command on apidef 8.33.1, the newest release, in generated/apidef-8.33.1.txt. It finds the same five entities, prints no warning, and marks the two /users/{userId} points with $action=users, so 8.33.1 hides the canonical path behind an action instead. With the guide file, 8.33.1 keeps that action, so check the release you pin.

Measure the coupling between handlers

coupling.mjs asks dependency-cruiser for the import graph of monolith/handlers and keeps the edges between handler modules.

node coupling.mjs
imports between handler modules
  accounts -> users
  comments -> posts
  orders -> products
  orders -> users

Orders imports a display-name helper from users and a price formatter from products. Accounts and comments import from modules in their own context, which costs nothing at the cut.

List the queries that cross resources

An import graph cannot see two modules that share a table. SQLite can: every table a statement opens appears in its EXPLAIN program as an OpenRead or OpenWrite step whose second operand is the table’s root page.2 joins.mjs runs EXPLAIN on each handler query against monolith/shop.db, once with foreign keys off and once with them on, and records which tables come from the statement and which from a key check.

export function tablesTouched(dbFile, sql) {
  const plain = new DatabaseSync(dbFile, { readOnly: true, enableForeignKeyConstraints: false })
  const checked = new DatabaseSync(dbFile, { readOnly: true, enableForeignKeyConstraints: true })
  try {
    const own = opened(plain, sql)
    const all = opened(checked, sql)
    return [...all].sort().map((tbl) => ({ tbl, via: own.has(tbl) ? 'statement' : 'foreign key' }))
  } finally {
    plain.close()
    checked.close()
  }
}

It loads those rows and the owner of each table from contexts.json into two temporary tables, then runs one query.

SELECT q.module,
       q.query,
       count(DISTINCT q.tbl) AS tables,
       count(DISTINCT CASE WHEN q.via = 'foreign key' THEN q.tbl END) AS through_keys,
       replace(group_concat(DISTINCT o.resource ORDER BY o.resource), ',', ', ') AS resources
FROM query_table q
JOIN table_owner o ON o.tbl = q.tbl
GROUP BY q.module, q.query
HAVING count(DISTINCT o.resource) > 1
ORDER BY tables DESC, q.module, q.query;
node joins.mjs
queries that touch more than one resource
  orders.loadOrder         5 tables: order, product, user
  accounts.deleteUser      3 tables, 2 through a foreign key: order, user
  orders.addItem           3 tables, 2 through a foreign key: order, product
  orders.createOrder       3 tables, 2 through a foreign key: order, user
  comments.createComment   2 tables, 1 through a foreign key: comment, post

orders.loadOrder is the pitfall: one statement over orders, order lines, products, users and addresses. The other four rows cross resources only through foreign keys. Deleting a user opens orders because a foreign key on orders.user_id points at it, so a split that puts orders in another database has to replace that check.3

A reference without a key is invisible here. posts.user_id and comments.user_id hold user ids with no REFERENCES clause, so no statement opens users. A test declares the key on posts.user_id, and posts.createPost then opens users and Publishing waits.

Cut only where the readings agree

contexts.json holds what the event-storming session decided: four contexts, the modules and resources in each, and the resource that owns each table.

{
  "contexts": {
    "Catalog": { "modules": ["products"], "resources": ["product"] },
    "Identity": { "modules": ["accounts", "users"], "resources": ["user"] },
    "Publishing": { "modules": ["comments", "posts"], "resources": ["comment", "post"] },
    "Sales": { "modules": ["orders"], "resources": ["order"] }
  },
  "tables": {

seams.mjs checks each context against all three readings. Spec: its modules serve every operation on its entities and no other. Code: no import crosses its boundary, in either direction. Data: no query touches its tables together with another context’s.

node seams.mjs
Catalog: wait
  spec  every operation served inside
  code  orders -> products
  data  orders.loadOrder, orders.addItem
Identity: wait
  spec  every operation served inside
  code  orders -> users
  data  orders.loadOrder, accounts.deleteUser, orders.createOrder
Publishing: cut
  spec  every operation served inside, refers to user_id (Identity)
  code  none
  data  none
Sales: wait
  spec  every operation served inside
  code  orders -> products, orders -> users
  data  orders.loadOrder, accounts.deleteUser, orders.addItem, orders.createOrder

Publishing is the cut. Its only reference out is the user_id key in its paths, a value rather than a join. Catalog and Identity look independent in the spec and wait on Sales, whose load query reads their tables and imports their modules. Until orders stops doing both, neither can move without it.

Carve the same seam in Kiota and Swagger Codegen

A team that generates its SDK with Kiota or Swagger Codegen meets the seam again in the client. generate.sh ran each of them twice on monolith/openapi.json. The first run covered the whole document and the second the Publishing paths alone, and the script committed a summary of each tree.

node generators.mjs
Kiota 1.39.0, whole document: 16 operations
  top-level builders: orders, products, user, users
Kiota, --include-path /users/{userId}/posts --include-path /users/{userId}/posts/**
  users/item/posts/index.ts                GET POST
  users/item/posts/item/comments/index.ts  GET POST
  users/item/posts/item/index.ts           GET
  navigation only: users/index.ts, users/item/index.ts
Kiota, --include-path /users/{userId}/posts/** alone
  users/item/posts/item/comments/index.ts  GET POST
  users/item/posts/item/index.ts           GET
Swagger Codegen 3.0.85, whole document: 16 operations
  API classes: AccountsApi, AdminApi, CatalogApi, CommentsApi, OrdersApi, PostsApi, UsersApi
Swagger Codegen, -Dapis=Posts,Comments
  CommentsApi  createComment listComments
  PostsApi     createPost listPosts loadPost
  models: Comment, CommentInput, Post, PostInput

Kiota builds its request builders from path segments, as its request builders page describes, so its four top-level builders match the four prefixes. --include-path gives a Publishing client from the same document. The glob /users/{userId}/posts/** alone left out the collection itself, the list and create on posts, so the seam run passes the bare path too. The users builders stay, without operations, because the call chain starts there.

On this document, Swagger Codegen 3.0.85 wrote one API class per tag, seven in all, AccountsApi and AdminApi among them. Selective generation with -Dapis=Posts,Comments, a -Dmodels list, and -DsupportingFiles gives the seam’s client. The typescript-fetch target keeps its API classes in api.ts, and without -DsupportingFiles the run wrote no file and exited 0. Neither tool reads the code or the tables, so neither replaces the overlay. Swagger Codegen shows the tag reading in the class list a client team works with, and Kiota’s kiota-lock.json keeps the include patterns beside the generated client.

Check it worked

The test fails if the overlay passes a context it should not. It feeds the overlay one extra import and one extra join, and the Publishing verdict must turn to wait. It also refuses an entity or a module no context claims, and a table no resource owns.

test('one new import or one new join turns the Publishing cut into a wait', () => {
  const a = inputs()
  a.edges.push({ from: 'comments', to: 'users' })
  assert.equal(verdicts(overlay(a)).Publishing, 'wait')
  const b = inputs()
  b.joins.push({ module: 'comments', query: 'listComments', tables: 2, resources: 'comment, user' })
  assert.equal(verdicts(overlay(b)).Publishing, 'wait')
})
node --test seams.test.mjs
1..16
# tests 16
# suites 0
# pass 16
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 690.548356

When it goes wrong

The join list is empty for a query you know joins. It is built at run time, so it never reached a handler’s queries. The finder reads only what each module declares, so move the SQL there.

A context passes that should not. The owner map in contexts.json names the wrong resource for a table, so the join looks internal. The finder refuses a table with no owner, and a wrong owner needs review.

The spec reading changes after an upgrade. apidef classifies by heuristics that move between releases, as the $action=users difference between 8.32.4 and 8.33.1 shows. Pin the version in the lockfile, and run the newest one in a recording step before you move to it.

When not to do this

Do not cut along resources because the spec says so. A path prefix is a promise to clients, not a statement about the data, and the order query here crosses three resources under one prefix.

Do not adopt apidef only to read your seams. If your client generator is Kiota, its path tree already gives the prefix reading, and --include-path gives a client per seam. If you use Swagger Codegen and your tags are service names, its class list is the tag reading with nothing else to install.

Do not trust an empty join list from a monolith whose SQL comes from an ORM. The queries exist only at run time, so record them from the test suite instead of from module exports.

Skip the overlay for a monolith with one team and three modules. The workshop and the scripts cost more than reading three folders.

Last verified

Verified 2026-11-22 against Node 22.23.5, @voxgig/apidef 8.32.4, dependency-cruiser 18.8.0, Kiota 1.39.0 and Swagger Codegen 3.0.85. Kiota and Swagger Codegen ran once, in generate.sh, and the page reads the summaries it committed. The two apidef 8.33.1 runs are from that script too. The apidef range a scaffold installs was read from the package.json template in @voxgig/create-sdkgen 0.31.9.

Footnotes

  1. Melvin Conway’s paper on how committees invent appeared in Datamation in April 1968. Its thesis, that organizations which design systems produce copies of their own communication structures, sits in the third-last paragraph. The author’s note on the reprint, written 42 years after publication, says this is perhaps the paper’s most remarkable feature. ↩︎ Back to text

  2. SQLite’s own page on EXPLAIN says its output is intended for interactive analysis and troubleshooting only. The format may change from one release to the next, the page adds, and programs should not use it. The join finder uses it anyway, and its test pins the five tables the order query must open. ↩︎ Back to text

  3. SQLite ships with foreign key constraints off, for backwards compatibility, and each connection turns them on for itself. Node 22’s DatabaseSync turns them on unless enableForeignKeyConstraints is false, so the same file answers EXPLAIN differently depending on who opened it, which is the difference joins.mjs measures. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.