Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,37 @@ All notable changes to Health Intersections FHIRsmith will be documented in this
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.0.9] - 2026-mm-dd

### Security

-

### Added

-

### Changed

-

### Fixed

-

### Removed

-

### Tx Conformance Statement

(paste)

## [1.0.8] - 2026-11-24

### Added

- Cluster: a heavy lane. A tx request with a body over `server.cluster.heavyLaneMinBytes` (1 MB, by its Content-Length) and no cache-id goes to one tx-worker (the last; `heavyLaneProcesses`, 1), which the other requests keep off while it has one: parsing a large body, and much of what is done with it, holds a process's event loop for seconds, and this keeps that to one process. On tx.fhir.org, bodies of tens of MB held every process's event loop for 2-5 s, once or twice a minute. 0 turns it off; it is logged at start ([cluster.md](cluster.md))
- Cluster: a heavy lane. A tx request with a body over `server.cluster.heavyLaneMinBytes` (1 MB, by its Content-Length), or in or for XML (`heavyLaneXml`: by `_format`, else `Accept`, or an XML body; XML is slow to read and write, and rare), and no cache-id goes to one tx-worker (the last; `heavyLaneProcesses`, 1), which the other requests keep off while it has one: parsing a large body, and much of what is done with it, holds a process's event loop for seconds, and this keeps that to one process. On tx.fhir.org, bodies of tens of MB held every process's event loop for 2-5 s, once or twice a minute. `heavyLaneMinBytes` 0 and `heavyLaneXml` false turn it off; it is logged at start ([cluster.md](cluster.md))

### Fixed

Expand Down
79 changes: 62 additions & 17 deletions cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@
* + Retry-After
* - lets cheap requests (by method and path: the fast lane) use fastLaneExtra more slots
* than maxOutstanding, ahead of the others, leaving them normalMinSlots
* - sends a tx request with a body over heavyLaneMinBytes (by Content-Length) and no cache-id
* to the heavy lane's process(es) (heavyLaneProcesses tx-workers, the last ones), and
* keeps other requests off such a process while it has one: parsing a large body (and
* the work on what it holds) holds a process's event loop for seconds, and this keeps that
* to one process
* - sends a tx request with a body over heavyLaneMinBytes (by Content-Length), or in or for
* XML (heavyLaneXml), and no cache-id to the heavy lane's process(es) (heavyLaneProcesses
* tx-workers, the last ones), and keeps other requests off such a process while it has one:
* parsing a large body (and the work on what it holds), or reading or writing a large
* resource as XML, holds a process's event loop for seconds, and this keeps that to one
* process
* - sends no new requests to a process that answered 503 for cooldownSeconds, while
* another can take them
* - answers 504 for a process that hasn't begun its response in upstreamTimeoutSeconds, and
Expand Down Expand Up @@ -127,6 +128,10 @@
// (2026-11-24: parsing them, then indexing the expansions in them) are tens of MB
const HEAVY_LANE_MIN_BYTES = 1024 * 1024;
const HEAVY_LANE_PROCESSES = 1;
// XML is read and written in JavaScript on the event loop, several times slower than JSON, and
// the largest responses are XML (ICD-10-CM, 13.7 MB). It is also rare: 67 of 46,000 requests
// on tx.fhir.org (2026-11-24), so the lane can take all of it
const HEAVY_LANE_XML = true;
const GB = (b) => (b / 2 ** 30).toFixed(1);
const HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'upgrade', 'te', 'trailer', 'expect'];

Expand Down Expand Up @@ -190,6 +195,12 @@
}
return n;
};
const flag = (value, name) => {
if (typeof value !== 'boolean') {
throw new Error(`server.cluster.${name} must be true or false, not '${value}'`);
}
return value;
};
if (!(statusSeconds > 0)) {
throw new Error(`server.cluster.statusSeconds must be a number of seconds above 0, not '${cluster.statusSeconds}'`);
}
Expand Down Expand Up @@ -218,6 +229,7 @@
normalMinSlots: Number(cluster.normalMinSlots ?? NORMAL_MIN_SLOTS),
heavyLaneMinBytes: count(cluster.heavyLaneMinBytes ?? HEAVY_LANE_MIN_BYTES, 'heavyLaneMinBytes'),
heavyLaneProcesses: count(cluster.heavyLaneProcesses ?? HEAVY_LANE_PROCESSES, 'heavyLaneProcesses'),
heavyLaneXml: flag(cluster.heavyLaneXml ?? HEAVY_LANE_XML, 'heavyLaneXml'),
statusMs: statusSeconds * 1000,
routing: { cacheAffinity: !sharedCache || cluster.cacheAffinity === true, sharedClosure: cluster.sharedClosure === true, sharedCache }
};
Expand Down Expand Up @@ -270,17 +282,48 @@
}

/**
* Whether a tx request takes the heavy lane (cluster.md), by its declared size (the launcher
* doesn't read bodies): a body with a Content-Length over minBytes (0: no lane). A chunked
* body has none, and doesn't (nginx, buffering the request, sends a Content-Length).
* Whether a request is in or for XML, as the server decides (acceptsXml in tx/tx.js): by
* _format (or format) in the query when there is one, else by Accept - XML unless it asks for
* HTML (a browser's Accept names XML too, after text/html). A body in XML (its Content-Type)
* is XML whatever the response is. _format=html/xml, the page's XML tab, is XML too: it renders
* the whole resource as XML. A _format in a form post's body is not seen (the launcher doesn't
* read bodies)
* @param {Object} req - url, headers
*/
function isXml(req) {
if (/xml/i.test(String(req.headers['content-type'] || ''))) {
return true;
}
const q = req.url.indexOf('?');
if (q >= 0) {
const params = new URLSearchParams(req.url.substring(q + 1));
const fmt = params.get('_format') || params.get('format');
if (fmt) {
return /xml/i.test(fmt);
}
}
const accept = String(req.headers.accept || '');
return !accept.includes('text/html') && /application\/(fhir\+xml|xml\+fhir|xml)/i.test(accept);
}

/**
* Whether a tx request takes the heavy lane (cluster.md): a body with a Content-Length over
* minBytes (0: not by size; the launcher doesn't read bodies, and a chunked body has none -
* nginx, buffering the request, sends one), or with xml, a request in or for XML (isXml).
* @param {Object} req - method, url, headers
* @param {string[]} txPaths
* @param {number} minBytes
* @param {boolean} [xml]
*/
function isHeavyLane(req, txPaths, minBytes) {
if (!(minBytes > 0) || txRest(req.url, txPaths) === null) {
function isHeavyLane(req, txPaths, minBytes, xml = false) {
if (txRest(req.url, txPaths) === null) {
return false;
}
const len = req.headers['content-length'];
return /^\d+$/.test(len || '') && Number(len) > minBytes;
if (minBytes > 0 && /^\d+$/.test(len || '') && Number(len) > minBytes) {
return true;
}
return xml && isXml(req);
}

/**
Expand Down Expand Up @@ -454,6 +497,7 @@
const normalMinSlots = Math.min(settings.normalMinSlots ?? NORMAL_MIN_SLOTS, maxOutstanding);
const heavyLaneMinBytes = settings.heavyLaneMinBytes ?? HEAVY_LANE_MIN_BYTES; // 0: no heavy lane
const heavyLaneProcesses = settings.heavyLaneProcesses ?? HEAVY_LANE_PROCESSES;
const heavyLaneXml = settings.heavyLaneXml ?? HEAVY_LANE_XML;
// what each process does: every one has a role (library/role.js)
const trimAllocator = (settings.memory && settings.memory.trimAllocator) ?? ROLE_TRIM_ALLOCATOR;
const command = settings.command || ((proc) => [process.execPath, [
Expand All @@ -474,7 +518,7 @@
// the heavy lane: the last heavyLaneProcesses tx-workers, if that leaves another process
// serving tx (otherwise every request would be in the lane, and there's no lane)
const laneWorkers = procs.filter(p => p.role === 'tx-worker').slice(-heavyLaneProcesses);
const heavyLane = heavyLaneMinBytes > 0 && heavyLaneProcesses > 0 && laneWorkers.length === heavyLaneProcesses &&
const heavyLane = (heavyLaneMinBytes > 0 || heavyLaneXml) && heavyLaneProcesses > 0 && laneWorkers.length === heavyLaneProcesses &&
procs.filter(p => p.servesTx).length > heavyLaneProcesses;
if (heavyLane) {
for (const p of laneWorkers) {
Expand Down Expand Up @@ -706,7 +750,7 @@
}
const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (proc.failures - 1));
log(`${proc.name} exited (${signal || code}); restarting in ${delay / 1000} s`);
proc.restartTimer = setTimeout(() => startProcess(proc), delay);

Check warning on line 753 in cluster.js

View workflow job for this annotation

GitHub Actions / Code Quality

Promise returned in function argument where a void return was expected
});
// ready: the process says so from its listen callback (server.js), on its own channel,
// so an old process still shutting down on the same port can't answer for it
Expand Down Expand Up @@ -839,7 +883,7 @@
const w = { req, res, route: classify(req.url, req.headers, settings.txPaths, settings.routing) };
w.fast = fastLaneExtra > 0 && w.route.to !== 'master' && isFastLane(req, settings.txPaths, fastLaneMaxBytes);
// a request with a cache-id goes to its owner, whatever its size
w.heavy = heavyLane && w.route.to === 'tx' && isHeavyLane(req, settings.txPaths, heavyLaneMinBytes);
w.heavy = heavyLane && w.route.to === 'tx' && isHeavyLane(req, settings.txPaths, heavyLaneMinBytes, heavyLaneXml);
if (send(w)) {
return;
}
Expand Down Expand Up @@ -1136,10 +1180,11 @@
log(`limits: maxOutstanding ${maxOutstanding}, queueSeconds ${queueMs / 1000}, ownerQueueSeconds ${ownerQueueMs / 1000}, cooldownSeconds ${cooldownMs / 1000}, upstreamTimeoutSeconds ${upstreamTimeoutMs / 1000}, writeTimeoutSeconds ${writeTimeoutMs / 1000}, ` +
`fastLaneExtra ${fastLaneExtra}, fastLaneMaxBytes ${fastLaneMaxBytes}, normalMinSlots ${normalMinSlots}, memoryHeadroomGB ${headroom / 2 ** 30}, drainSeconds ${settings.drainMs / 1000}, ` +
`trimAllocator ${trimAllocator}, statusSeconds ${statusMs / 1000}, recycleSeconds ${recycleMs / 1000}` + (recycleMs > 0 ? ` (a tx-worker ${memory.describe} that long, with no request at work, is restarted)` : ' (never)'));
const laneRules = [heavyLaneMinBytes > 0 ? `with a body over ${heavyLaneMinBytes} bytes` : null, heavyLaneXml ? 'in or for XML' : null].filter(r => r);
log(heavyLane
? `heavy lane: tx requests with a body over ${heavyLaneMinBytes} bytes and no cache-id go to ${laneWorkers.map(p => p.code).join(', ')}, ` +
'which other requests avoid while it has one (heavyLaneMinBytes, heavyLaneProcesses)'
: `heavy lane: off (${heavyLaneMinBytes > 0 && heavyLaneProcesses > 0 ? `it needs more than ${heavyLaneProcesses} process(es) serving tx, ${heavyLaneProcesses} of them tx-workers` : 'heavyLaneMinBytes or heavyLaneProcesses is 0'})`);
? `heavy lane: tx requests ${laneRules.join(' or ')}, without a cache-id, go to ${laneWorkers.map(p => p.code).join(', ')}, ` +
'which other requests avoid while it has one (heavyLaneMinBytes, heavyLaneXml, heavyLaneProcesses)'
: `heavy lane: off (${laneRules.length > 0 && heavyLaneProcesses > 0 ? `it needs more than ${heavyLaneProcesses} process(es) serving tx, ${heavyLaneProcesses} of them tx-workers` : 'heavyLaneMinBytes is 0 and heavyLaneXml false, or heavyLaneProcesses is 0'})`);
if (recycleMs > 0) {
memoryTimer = setInterval(checkMemory, settings.recycleCheckMs || RECYCLE_CHECK_MS);
memoryTimer.unref();
Expand Down Expand Up @@ -1307,8 +1352,8 @@
process.exit(1);
}
const shutdown = () => launcher.stop().then(() => process.exit(0));
process.on('SIGTERM', shutdown);

Check warning on line 1355 in cluster.js

View workflow job for this annotation

GitHub Actions / Code Quality

Promise returned in function argument where a void return was expected
process.on('SIGINT', shutdown);

Check warning on line 1356 in cluster.js

View workflow job for this annotation

GitHub Actions / Code Quality

Promise returned in function argument where a void return was expected
await launcher.start();
}

Expand All @@ -1319,4 +1364,4 @@
});
}

module.exports = { loadSettings, classify, isFastLane, isHeavyLane, laneProcs, pickTarget, createLauncher, memorySampler, childExecArgv };
module.exports = { loadSettings, classify, isFastLane, isHeavyLane, isXml, laneProcs, pickTarget, createLauncher, memorySampler, childExecArgv };
19 changes: 14 additions & 5 deletions cluster.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,15 +219,23 @@ cookie would be lost (see [nginx.md](nginx.md#headers-to-pass-to-the-server)).
searches and `$expand` never do. A request in the lane that turns out to be costly (a
`GET $validate-code` against a value set that must be expanded) costs at most `fastLaneExtra`
more requests at once on a process
* keeps large requests to a heavy lane. A tx request with a body over `heavyLaneMinBytes`
(1 MB, by its `Content-Length`) and no cache-id goes only to the lane's process: the last
* keeps large requests, and XML, to a heavy lane. A tx request with a body over
`heavyLaneMinBytes` (1 MB, by its `Content-Length`), or in or for XML (`heavyLaneXml`), and
no cache-id goes only to the lane's process: the last
`heavyLaneProcesses` (1) tx-worker(s), `tx2` with two workers. While the lane's process has
one, other requests don't go to it; when it has none, it takes its share like any other.
Parsing a large body holds a process's event loop for as long as it takes, and so does
much of what is done with what it holds (a large expansion sent as `tx-resource`, say): on
tx.fhir.org, bodies of tens of MB held it for 2-5 s, once or twice a minute on every
process (2026-11-24). The lane keeps that to one process, and the requests on it wait for
each other. A validator's usual requests, with value sets inline, are 10-100 KB. A request
each other. A validator's usual requests, with value sets inline, are 10-100 KB. XML is
read and written in JavaScript on the event loop, several times slower than JSON, and the
largest responses are XML (ICD-10-CM, 13.7 MB); it is also rare (67 of 46,000 requests on
tx.fhir.org), so the lane takes all of it, whatever its size. A request is XML as the server
decides it: by `_format` (or `format`) in the query if there is one, else by `Accept`
(`application/fhir+xml`, `application/xml+fhir` or `application/xml`, unless it also names
`text/html`, as a browser's does); `_format=html/xml` (the page's XML tab) counts too, and
so does a body whose `Content-Type` is XML. A `_format` in a form post's body isn't seen. A request
with a cache-id goes to the process that issued it, whatever its size. A chunked body has no
`Content-Length` and doesn't take the lane: nginx, buffering the request (its default),
sends one. While the lane's process isn't ready, its requests go to any process. There is
Expand Down Expand Up @@ -488,8 +496,9 @@ behind nginx), the page shows, and empties, only the process the request reached
| `server.cluster.recycleSeconds` | | 30 | Seconds a tx-worker may stay over the memory guard's refusal threshold with no request at work before the launcher restarts it. 30: long enough for the guard's own recovery (a forced last-resort GC and `malloc_trim` at once and again 5 s later, `malloc_trim` alone up to once a second) to have its effect, short next to a client's retries; meanwhile every request to the server is refused. The restart costs the worker's caches (see [Limits](#limits-of-this-arrangement)) and the about 15 s it takes to start; the others serve meanwhile, and the gate opens once the old process has exited. 0: never. |
| `server.cluster.fastLaneExtra` | | 4 | How many more than `maxOutstanding` a process may have when the request is in the fast lane (above). 4: room for the cheap requests of a surge without letting a lane request that turns out to be costly crowd a process. 0: no fast lane. |
| `server.cluster.normalMinSlots` | | 4 | While other requests wait, the fast lane leaves each process enough slots for this many of them to run, so heavy work keeps going during a flood of cheap requests. 4: in a 3x surge on 4 CPUs (1 master + 2 workers) the heavy requests answered were the same with 4, 8 or no minimum (about 7,100-7,400 in 30 s), but each heavy request running slows the cheap ones on its event loop: the `$lookup` probe took 88 ms (median) with 4, 150-210 ms with 8. With the lane held to 4 slots of its own, the surge was served at 457/s, not about 1,200/s, and the probe took 1.1 s. 0: no minimum. At most `maxOutstanding`. |
| `server.cluster.heavyLaneMinBytes` | | 1048576 | A tx request with a body bigger than this (its `Content-Length`, in bytes) and no cache-id goes to the heavy lane (above). 1 MB: a validator's usual requests are 10-100 KB, and a body that takes long to parse is tens of MB. Logged at start. 0: no lane. |
| `server.cluster.heavyLaneProcesses` | | 1 | How many tx-workers (the last ones) are the heavy lane. 1: large requests are rare, and every process in the lane is one whose other requests wait behind them. There is no lane unless more processes than this serve tx. 0: no lane. |
| `server.cluster.heavyLaneMinBytes` | | 1048576 | A tx request with a body bigger than this (its `Content-Length`, in bytes) and no cache-id goes to the heavy lane (above). 1 MB: a validator's usual requests are 10-100 KB, and a body that takes long to parse is tens of MB. Logged at start. 0: not by size (with `heavyLaneXml` false as well, no lane). |
| `server.cluster.heavyLaneXml` | | true | Whether a tx request in or for XML (no cache-id) goes to the heavy lane (above), whatever its size. true: XML is slow to read and write, and rare. false: XML goes anywhere, unless its body is over `heavyLaneMinBytes`. |
| `server.cluster.heavyLaneProcesses` | | 1 | How many tx-workers (the last ones) are the heavy lane. 1: large requests and XML are rare, and every process in the lane is one whose other requests wait behind them. There is no lane unless more processes than this serve tx. 0: no lane. |
| `server.cluster.fastLaneMaxBytes` | | 1024 | The largest `Content-Length` with which a `POST` `$lookup`, `$subsumes` or `$validate-code` takes the fast lane. 1024: a single coding with its parameters is about 450 bytes; an inline value set or code system is larger. Half of a validator's calls are such `POST CodeSystem/$validate-code`s, and with them in the lane a 3x surge on 4 CPUs was served at twice the rate (1210/s vs 608/s, with the same CPU) and they took 24 ms instead of 1 s; the other requests did no worse. 0: a `POST` never does. |
| `server.memory.trimAllocator` | | true with a role; false without | Whether a process calls `malloc_trim` (Linux with glibc, and the optional `koffi` dependency): with a role, once after loading the library (it gives back 0.6-0.7 GB a process), and while the memory guard is refusing (see [Memory](#memory)). true: the C allocator keeps freed memory resident, and no GC touches it. false with a role: for diagnosis. Without a role it is off unless set true. Each process's memory line at start says whether it is on. |
| `modules.tx.instanceCode` | | `m0` under the launcher | The master's instance code. The workers are `tx1`, `tx2`, ... The `m0` default is the launcher's: a master started by hand needs this, `--instance-code` or `FHIRSMITH_INSTANCE_CODE` (see [Roles](#roles)). |
Expand Down
1 change: 1 addition & 0 deletions library/config-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ const SERVER = obj({
fastLaneMaxBytes: count(),
heavyLaneMinBytes: count(),
heavyLaneProcesses: count(),
heavyLaneXml: bool(),
statusSeconds: positive(),
sharedCache: bool(),
sharedCacheMaxMB: num({ min: 0 }),
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fhirsmith",
"version": "1.0.8",
"version": "1.0.9-snapshot",
"txVersion": "1.11.1-snapshot",
"description": "A Node.js server that provides a collection of tools to serve the FHIR ecosystem",
"main": "server.js",
Expand Down
Loading
Loading