Extracting a Notification Service From a Monolith Without Rewriting the Caller
The usual story about extracting a service from a monolith is like this: You pick a module with set rules. You stand it up as its own deployment, then spend two sprints on the part nobody budgeted for; for example, repla
The usual story about extracting a service from a monolith is like this: You pick a module with set rules. You stand it up as its own deployment, then spend two sprints on the part nobody budgeted for; for example, replacing a function call with an API.
That is where the work actually is. The module was fine, and what you have to build is a REST endpoint on one side, a client on the other, request and response shapes that didn't exist before, serialization in both directions, and error handling for failures that couldn't happen before. Every call site that used to be one line becomes a network call you now own.
None of that is why you extracted the module. You extracted it because it needed to scale on its own, or because another team should own it, or because a slow email provider was holding up your request threads.
In this blog post, you will learn a different route. We will build a notification module inside a modular monolith, extract it into a standalone service, and watch the calling code stay almost the same. Then we will flip between the two services with one environment variable.
What you will learn
- Why extracting a module from a monolith normally creates integration work
- How Graftcode separates the callable interface from where a module runs
- How to run the same module in process and as a remote service using the same client
- What actually changes in your deployment, and what stays the same in your code
- Why this is useful for a gradual move toward microservices
- Which distributed system concerns this does not remove
Prerequisites
- Node.js 22 or higher installed locally
- Basic Node.js and JavaScript module knowledge
- Graftcode Gateway installed and on your local machine
Install Gateway with the installer script:
curl -fsSL <https://grft.dev/get> | sh
On Windows:
iwr <https://grft.dev/get> | iex
You can also get a release from Graftcode's releases on GitHub. Verify it using this command:
gg --help
No Graftcode account is needed. Everything here runs locally.
Why extraction normally costs so much
Start with the before picture. Inside a monolith, one module calls another like this:
const { NotificationService } = require("./src/notificationService");
const result = NotificationService.sendNotification(userId, "email", subject);
One require. One synchronous call. Your editor enforces the signature. Rename a parameter and every call site updates with it. Nothing can be out of sync because there is only one copy.
Now extract NotificationService into its own deployment. Here is everything you have to build that did not exist before:
Both of those columns exist only to move three arguments and one return value across a process boundary. The notification logic did not change at all.
That is the tax on extraction, and it is why "we should split that out" stays on the backlog. The module is ready. The integration work is what nobody wants to sign up for.
What Graftcode changes
Graftcode separates two things that usually travel together. The interface you call and where the code runs.
A module's public methods become its callable surface. Graftcode Gateway loads the module, discovers that surface, and publishes it. Consumers install a generated, typed package called a Graft and call the methods directly. Four terms, used throughout this post:
- Receiver is the module being called, in our case the notification module. Its public methods are the contract.
- Caller is the application doing the calling, in our case the invoicing app.
- Graft is the generated package the Caller installs with npm. You never write it.
- Gateway is the process that hosts the Receiver and publishes its surface.
What matters for extraction is that the Graft does not care where the Receiver runs. Execution mode is configuration. The Graftcode docs name three modes, and the precision is useful:
-
inmemoryruns the Receiver in the Caller's own process with no network hop -
ws://localhost:8090/wsis a WebSocket on the loopback interface, which is a real network transport -
ws://notifications.internal:80/wsis a remote host
People call all three "local". Only the first is actually in process.
So extraction stops being a rewrite. It becomes a deployment change plus a configuration value.
What we are building
A small invoicing application with a notification module, exposing three methods:
| Method | Purpose |
|---|---|
sendNotification(userId, channel, subject) |
Deliver on a channel, respecting the user's preferences |
getNotificationPreferences(userId) |
The user's email, push, and digest settings |
markAsRead(userId, notificationId) |
Mark one notification read and return the unread count |
And an InvoiceService that calls it when an invoice is issued.
We will go through three stages:
-
Monolith: Both modules in one project with a plain
require. No Graftcode in the calling code at all. - Extracted: The notification module gets its own Gateway and the app installs its Graft.
- Either on demand: One environment variable decides whether the module runs in process or remotely.
Stage 1: Build the modular monolith
Create the app:
mkdir -p graftcode-notification-extraction/app/src
cd graftcode-notification-extraction/app
npm init -y
Create src/notificationService.js. This is the module we will extract later, so notice that it already has decent boundaries. It owns its data and enforces its own rules.
const preferences = {
"user-1001": { email: true, push: true, digest: "daily" },
"user-1002": { email: true, push: false, digest: "weekly" },
"user-1003": { email: false, push: true, digest: "off" },
};
const inbox = [
{ id: "notif-1", userId: "user-1001", channel: "email", subject: "Your invoice is ready", read: false },
{ id: "notif-2", userId: "user-1001", channel: "push", subject: "Amara commented on your project", read: false },
{ id: "notif-3", userId: "user-1002", channel: "email", subject: "Weekly digest", read: true },
];
let counter = inbox.length;
class NotificationService {
static sendNotification(userId, channel, subject) {
const prefs = preferences[userId];
if (!prefs) {
return JSON.stringify({ ok: false, reason: "UNKNOWN_USER" });
}
if (channel === "email" && !prefs.email) {
return JSON.stringify({ ok: false, reason: "EMAIL_OPTED_OUT" });
}
if (channel === "push" && !prefs.push) {
return JSON.stringify({ ok: false, reason: "PUSH_OPTED_OUT" });
}
counter += 1;
const notification = { id: `notif-${counter}`, userId, channel, subject, read: false };
inbox.push(notification);
return JSON.stringify({ ok: true, notification });
}
static getNotificationPreferences(userId) {
const prefs = preferences[userId];
if (!prefs) {
return JSON.stringify({ userId, found: false });
}
return JSON.stringify({ userId, found: true, ...prefs });
}
static markAsRead(userId, notificationId) {
const match = inbox.find((n) => n.userId === userId && n.id === notificationId);
if (!match) {
return JSON.stringify({ ok: false, reason: "NOT_FOUND" });
}
match.read = true;
const unread = inbox.filter((n) => n.userId === userId && !n.read).length;
return JSON.stringify({ ok: true, id: match.id, unreadRemaining: unread });
}
}
module.exports = { NotificationService };
Three choices here are what make extraction cheap later on.
In this context; only the class is exported. preferences, inbox, and counter are module internals. When this becomes a Receiver, its callable surface will be exactly the three methods. Export them, and they would land on the contract.
The methods are static and take primitives; static input-to-output operations are independently routable. Every parameter and return is a string, which keeps the contract on the portable baseline Graftcode recommends: primitives, strings, and plain models, with identifiers and dates as strings.
Also, the opt-out rules live inside the module. The notification module decides EMAIL_OPTED_OUT, not its callers. That is what makes it a real boundary rather than a folder.
Now create an index.jsfile, the application that uses it:
const { NotificationService } = require("./src/notificationService");
class InvoiceService {
static issueInvoice(userId, amountCents) {
const subject = `Invoice for ${(amountCents / 100).toFixed(2)} is ready`;
const delivery = NotificationService.sendNotification(userId, "email", subject);
return JSON.stringify({
invoiceId: `inv-${Date.now()}`,
userId,
amountCents,
delivery: JSON.parse(delivery),
});
}
}
module.exports = { InvoiceService };
Point package.json at it:
{
"name": "invoicing-app",
"version": "1.0.0",
"main": "index.js"
}
Run it using this command:
node -e "const {InvoiceService} = require('./index.js'); console.log(InvoiceService.issueInvoice('user-1001', 24990));"
{"invoiceId":"inv-1791806826759","userId":"user-1001","amountCents":24990,
"delivery":{"ok":true,"notification":{"id":"notif-4","userId":"user-1001",
"channel":"email","subject":"Invoice for 249.90 is ready","read":false}}}
This is a monolith. One process, one require, a direct synchronous call. There is no Graftcode in this code yet, which is the point. You did not adopt anything to get here.
You can also host the whole thing through Gateway if you want both modules callable while they share a process:
gg ./package.json --port 8080 --httpPort 8081
Gateway discovers both InvoiceService and NotificationService and exposes them. Open http://localhost:8081/GV, and you will see both. A modular monolith whose modules are individually callable.
Stage 2: Extract the notification module
Now a reason to extract shows up. Email delivery is slow; the notification module needs to scale on its own, and a different team will own it.
Give it its own project and its own package.json:
cd ..
mkdir notification-service
cd notification-service
cp ../app/src/notificationService.js ./index.js
{
"name": "notification-service",
"version": "1.0.0",
"main": "index.js",
"license": "ISC"
}
Start a Gateway for it on its own ports:
gg ./package.json --port 8090 --httpPort 8091
In the log, look for the discovered type and the install commands:
[Info] Type enabled: NotificationService
[Info] Hosted module notification-service installation commands:
FOR NPM PROJECT:
npm install --registry <https://grft.dev/><your-registry-id>__free @graft/[email protected]
The module is now an independent service with its own Vision at http://localhost:8091/GV, its own ports, and its own lifecycle. Restart it without restarting the app.
One warning before you build on this. Without a Project Key the registry ID can change when Gateway restarts, and changing the exposed surface can change the generated package name. The docs cover this in Known limitations. For a tutorial it does not matter. For anything real, create a free project at portal.graftcode.com and pass --projectKey YOUR_PROJECT_KEY so consumers get a stable address.
Now install its Graft in the app:
cd ../app
npm install --registry <https://grft.dev/><your-registry-id>__free @graft/[email protected]
Stage 3: The only code change
Here is the whole diff on the calling side. Before:
const { NotificationService } = require("./src/notificationService");
class InvoiceService {
static issueInvoice(userId, amountCents) {
const subject = `Invoice for ${(amountCents / 100).toFixed(2)} is ready`;
const delivery = NotificationService.sendNotification(userId, "email", subject);
// ...
}
}
After:
const {
GraftConfig,
NotificationService,
} = require("@graft/npm-notification-service");
GraftConfig.setConfig(process.env.GRAFT_CONFIG);
class InvoiceService {
static async issueInvoice(userId, amountCents) {
const subject = `Invoice for ${(amountCents / 100).toFixed(2)} is ready`;
const delivery = await NotificationService.sendNotification(userId, "email", subject);
// ...
}
}
Four changes, and that is all of them:
- The
requirepath points at the Graft instead of the local file - One
GraftConfig.setConfig(...)line reads the topology from the environment - The method is now
async - The call is now
awaited
The method name, the arguments, the return shape, and the business logic are all unchanged. There is no URL in this file, no HTTP client, no request body, no response parsing, and no serialization code.
The async and await are unavoidable. Graftcode's generated Node.js Caller API is asynchronous even when the Receiver method is synchronous, and crossing a process boundary really is asynchronous work. If your call sites are deep in synchronous code, this is the one place extraction reaches into your codebase. Worth knowing before you plan the work.
Note what we did not do. We did not hardcode the host. GraftConfig.setConfig(process.env.GRAFT_CONFIG) is what makes the next section possible.
Stage 4: Run it remotely
GRAFT_CONFIG="name=@graft/npm-notification-service;modules=notification-service;runtime=nodejs;host=ws://localhost:8090/ws" \
node -e "const {InvoiceService} = require('./index.js'); InvoiceService.issueInvoice('user-1001', 24990).then(r => {console.log(r); process.exit(0);});"
{"invoiceId":"inv-1791806917917","userId":"user-1001","amountCents":24990,
"delivery":{"ok":true,"notification":{"id":"notif-4","userId":"user-1001",
"channel":"email","subject":"Invoice for 249.90 is ready","read":false}}}
Same output as the monolith. The notification now happens in a different process over a WebSocket, and the calling code does not know.
Stage 5: Run the same code in process
Now flip the topology back without touching the file:
GRAFT_CONFIG="name=@graft/npm-notification-service;modules=/absolute/path/to/app/src/notificationService.js;runtime=nodejs;host=inmemory" \
node -e "const {InvoiceService} = require('./index.js'); InvoiceService.issueInvoice('user-1003', 5000).then(r => {console.log(r); process.exit(0);});"
{"invoiceId":"inv-1791806927276","userId":"user-1003","amountCents":5000,
"delivery":{"ok":false,"reason":"EMAIL_OPTED_OUT"}}
The module ran inside the calling process. No Gateway on 8090 was involved. The rule still held too. user-1003 has email: false, so the notification module refused the delivery exactly as it would have remotely.
Put the two configurations side by side, because this is the point of the post:
# Monolith, in process
name=@graft/npm-notification-service;modules=/path/to/app/src/notificationService.js;runtime=nodejs;host=inmemory
# Microservice, remote
name=@graft/npm-notification-service;modules=notification-service;runtime=nodejs;host=ws://localhost:8090/ws
Two things differ: host and modules.
host picks the execution path. modules changes meaning based on that choice. In remote mode, it names the hosted module on the Gateway. In inmemory mode it must be a filesystem path to the actual JavaScript file, because the module now loads into your process. Whether a Graft ships the Receiver module for in-memory use is package dependent. The one in this tutorial does not, which I confirmed by looking inside node_modules, so modules points at the local file.
This works because the generated package resolves configuration through six source levels. Lower numbers win:
| Priority | Source |
|---|---|
| 1 | Graft specific environment variable |
| 2 | Global environment variable (GRAFTCODE_CONFIG) |
| 3 | Graft specific file (.json, .yaml, .txt) |
| 4 | Global file (graftcode-config.json, .yaml, .txt) |
| 5 | Programmatic setConfig(...)
|
| 6 | Generated library default |
Our setConfig(...) call lands at priority 5 and overrides the library default at 6, which is host=inmemory. In a real deployment, you would use level 1 or 2 and skip setConfig entirely. Then your orchestrator decides the topology and the application code holds no configuration at all.
One caveat will cost you an afternoon if you miss it. Set configuration before the first call. The runtime context is cached once it initializes, and there is no supported reset. Configuration applied after your first method call is ignored.
Stage 6: Prove the remote call is actually remote
Confirm that remote mode is not quietly falling back to something local. Stop the notification Gateway:
# stop the gg process listening on 8090
Then run in remote mode again:
ERROR: WebSocket send to ws://localhost:8090/ws failed after 2 attempts.
Last error: WebSocket connection to ws://localhost:8090/ws failed:
Check that the server is running, the URL is correct (ws:// or wss://),
and that no firewall or proxy is blocking the connection.
Start it again and the call succeeds. The code never changed. Only the topology did.
That failure is the most honest thing in the tutorial, and it leads straight into the next section.
Try it locally
Here is the whole runbook in one place. It is also the fastest way to see the point of the post. You will run the same application file twice against two different topologies, changing nothing but an environment variable.
Terminal 1, host the extracted notification service:
cd graftcode-notification-extraction/notification-service
gg ./package.json --port 8090 --httpPort 8091
Point gg at the package root, not at a specific .js file. The analyzer copies the directory of the path you pass, then looks for a package.json inside it. Hand it a file in a subdirectory and you get package.json not found after copying.
Terminal 2, run the application against the remote service:
cd graftcode-notification-extraction/app
GRAFT_CONFIG="name=@graft/npm-notification-service;modules=notification-service;runtime=nodejs;host=ws://localhost:8090/ws" \
node -e "const {InvoiceService} = require('./index.js'); InvoiceService.issueInvoice('user-1001', 24990).then(r => {console.log(r); process.exit(0);});"
{"invoiceId":"inv-1791809215976","userId":"user-1001","amountCents":24990,
"delivery":{"ok":true,"notification":{"id":"notif-4","userId":"user-1001",
"channel":"email","subject":"Invoice for 249.90 is ready","read":false}}}
Now run the identical file in process. Same terminal, same command, different GRAFT_CONFIG:
GRAFT_CONFIG="name=@graft/npm-notification-service;modules=$PWD/src/notificationService.js;runtime=nodejs;host=inmemory" \
node -e "const {InvoiceService} = require('./index.js'); InvoiceService.issueInvoice('user-1003', 5000).then(r => {console.log(r); process.exit(0);});"
{"invoiceId":"inv-1791809223338","userId":"user-1003","amountCents":5000,
"delivery":{"ok":false,"reason":"EMAIL_OPTED_OUT"}}
user-1003 was refused because they opted out of email. That rule lives in the notification module, and it held in both structure, which is exactly what you want to verify after an extraction.
You can also have a look at some of the modules in notification-service:
What commonly goes wrong:
-
modulesmeans two different things depending onhost. Remote mode wants the hosted module name.inmemorymode wants a real filesystem path, since the module loads into your process. Mixing them up is the most common failure. - The in-process command uses
$PWDso you do not have to paste an absolute path. It only works from theappdirectory. - Nothing prints if you forget the
node -erunner.app/index.jsonly exportsInvoiceService. It does not call it.
What changed in deployment, what stayed in code
Changed in deployment:
- A second Gateway process, with its own ports and lifecycle
- A second thing to build, ship, monitor, and page someone about
- A network hop on the invoice path
- One environment variable per Caller
- A registry dependency for the Graft install
Stayed the same in code:
- Every method name and signature
- The notification business rules, in one place
- The invoice logic
- The call sites, apart from
asyncandawait
Never written:
- A controller or route handler
- Request and response DTOs
- An HTTP client or fetch wrapper
- Serialization and parsing
- An OpenAPI spec or a codegen step
That middle list is what normally takes the two sprints.
What Graftcode does not remove
I want to be direct here, because "extract a service by changing one environment variable" reads as a bigger claim than it is. The integration layer is gone. The distributed system is not.
Authentication and authorization are yours: Graftcode lists invocation authentication as Alpha and says plainly that if nothing is configured, no invocation authentication occurs. A Project Key is publication identity, not runtime call authorization. In this tutorial, anyone who can reach port 8090 can call sendNotification for any user. Fine on localhost, unacceptable anywhere else. See Authenticate Graft calls.
Failure handling is yours: You saw the connection error above. In the monolith, that failure mode did not exist. Now it does, and there is no built-in retry, backoff, failover, or idempotency. Retrying an invocation can repeat its effects, which for a notification service means sending the same email twice. Design for it. Use explicit operation IDs for deduplication, and only retry operations you made idempotent on purpose.
Timeouts are yours: There is no cross-runtime cancellation and no global invocation timeout option on Gateway. Apply timeouts in Caller code and in infrastructure.
Observability is yours: Gateway exposes GET /status for liveness and nothing more. There is no metrics collector, no log collector, and no readiness or dependency health endpoint. W3C Trace Context propagation exists for .NET and Node.js, but you instrument both sides yourself and check that the spans actually connect.
In process state becomes per-instance state: The inbox array lives in module scope. In the monolith, that was one array. With one Gateway it is still one array. Run two Gateway instances, and you have two. Extraction forces a state question you could previously ignore, and no amount of configuration answers it for you.
Contract changes still need care: Grafts update through npm, which is a good workflow, but nothing guarantees an old Caller works against a new Receiver. Even additive source changes can change generated names or exports. Pin versions, regenerate deliberately, and smoke test a few Callers.
Graftcode is in Alpha: Support is directional and framework complex types are rejected on the public surface. This tutorial returns JSON strings to stay on the portable baseline. That is a real tradeoff you make in exchange for predictability.
Conclusion
The notification module in this tutorial never changed. It started as a file the invoicing app required directly. It ended as a standalone service with its own Gateway, its own ports, and its own deploy cycle. The calling code picked up an async, an await, and one configuration line.
That is the useful separation. The callable interface is the module's public methods, and where the module runs is a deployment detail. Keeping those independent is what turns extraction from a rewrite into a config change.
The distributed system concerns did not disappear, and you should plan for them. But they were always going to be there. The integration layer was pure overhead, and that is the part you can stop writing.
Thanks for reading. If you try this on a real module, I would like to hear where the boundary turned out to be wrong, because that is the interesting failure mode here.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.



