> For the complete documentation index, see [llms.txt](https://boxlang.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://boxlang.ortusbooks.com/boxlang-framework/clustering-services.md). Agents can also search and read this documentation through its [MCP server](https://boxlang.ortusbooks.com/~gitbook/mcp).

# Clustering Services

BoxLang Clustering Services let nodes find each other and coordinate through a shared cache, with node identity, heartbeats, open node attributes and a view of the fleet

{% hint style="success" %}
**New in BoxLang 1.20.0.** Clustering Services are a runtime service of their own. [Clustered Scheduled Tasks](https://boxlang.ortusbooks.com/boxlang-framework/asynchronous-programming/clustered-scheduled-tasks.md) are the first feature built on it.
{% endhint %}

When you run the same application on many servers, the servers need to know about each other. **BoxLang Clustering Services** give every BoxLang node that ability. Nodes join a named cluster through a shared cache, publish who they are and what they are doing, and see their peers.

The service is deliberately separate from the scheduler. It owns **membership and node records**, and it hands data back to whoever asks. It never decides anything. Features built on top of it bring their own policy.

## 🧭 What the Service Gives You

| Capability                   | Description                                                                                                                  |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| **Node identity**            | Every node has an id, `{hostname}-{pid}` by default, or the `nodeId` you configure.                                          |
| **Named clusters**           | Nodes with the same `cluster.name` see each other. Different names never do, so one shared cache can serve several clusters. |
| **Membership and heartbeat** | Each node rewrites its own record in the shared cache on every heartbeat.                                                    |
| **Node attributes**          | An open struct on each node record. Any feature can add keys of any type, and the feature that adds them owns their meaning. |
| **A view of the fleet**      | A lazily refreshed snapshot of every node, with helpers to read one node, the peers, or one attribute.                       |
| **Any shared store**         | Coordination goes through a BoxLang cache backed by a store every node can see.                                              |

```mermaid
flowchart LR
    A["Node A"] <--> C[("Shared cache<br/>bxcluster")]
    B["Node B"] <--> C
    D["Node C"] <--> C
    C -.->|"node records and attributes"| A
```

## 🚀 Quick Start

Enable the `cluster` block in `boxlang.json` on every node, and point `cacheName` at a cache that all nodes can reach.

```json
{
    "cluster": {
        "enabled": true,
        "name": "production",
        "cacheName": "bxcluster",
        "heartbeatSeconds": 5
    },
    "caches": {
        "bxcluster": {
            "provider": "Redis",
            "properties": { "host": "redis.internal.example.com", "port": "6379" }
        }
    }
}
```

| Setting            | Default       | Purpose                                                                                                                            |
| ------------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`          | `false`       | Master switch for this node.                                                                                                       |
| `nodeId`           | `null`        | This node's identity. When `null`, BoxLang uses `{hostname}-{pid}`. Set it when your platform gives you a stable pod or task name. |
| `name`             | `"default"`   | The cluster name.                                                                                                                  |
| `cacheName`        | `"bxcluster"` | The coordination cache.                                                                                                            |
| `heartbeatSeconds` | `5`           | How often this node rewrites its record. Must be greater than zero.                                                                |

{% hint style="warning" %}
The bundled `default` cache is local to each JVM. Nodes sharing it never see each other. Use Redis, a JDBC store, or a `FileSystemStore` on a shared volume. See the full [Cluster configuration](https://boxlang.ortusbooks.com/getting-started/configuration/cluster.md) reference.
{% endhint %}

At startup, BoxLang proves the coordination cache works by writing a value, reading it back and removing it. A misconfigured cache shows up immediately, not as a failed claim minutes later.

## 🪪 The Node Record

Each node writes one record to the shared cache on every heartbeat.

| Field                 | Description                                      |
| --------------------- | ------------------------------------------------ |
| `nodeId`              | The node's identity.                             |
| `hostname`            | The host name of the machine.                    |
| `ip`                  | The local IP address.                            |
| `startedAt`           | When this node started.                          |
| `heartbeatAt`         | The time of the latest heartbeat.                |
| `attributesUpdatedAt` | When the node's attributes were last refreshed.  |
| `attributes`          | The open struct that features add their data to. |

The record expires if the node stops beating, so a node that disappears drops out of the fleet on its own. A node is considered gone after three missed beats.

## 🏷️ Node Attributes

`attributes` is an open struct. Any feature can add any key of any type, and the feature that added a key owns what it means. The scheduler, for example, publishes `scheduler.taskSeconds`, a rolling measure of how busy the node is, so peers can share work by load.

There are three ways to add attributes.

### Push: set them directly

Hold the service and write to it whenever you like. The next record write picks up whatever is there.

| Method                        | Behavior                                                                                                                                                      |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setAttribute( path, value )` | Sets one attribute by dotted path, such as `perf.stats.cpu.avgLoad`, creating intermediate structs as needed.                                                 |
| `mergeAttributes( struct )`   | Merges a struct in, shallowly, key by key.                                                                                                                    |
| `removeAttribute( path )`     | Removes one attribute by dotted path. A feature that stops reporting a metric should remove the key rather than leave a stale value that others keep reading. |
| `getLocalAttributes()`        | Returns this node's live attributes struct **by reference**.                                                                                                  |

```java
ClusterService cluster = BoxRuntime.getInstance().getClusterService();

cluster.setAttribute( "perf.cpu.load", 0.42 );
cluster.mergeAttributes( Struct.of( Key.of( "region" ), "us-east" ) );
cluster.removeAttribute( "perf.cpu.load" );
```

### Contribute: register a supplier

A component can publish data without any interceptor machinery. Register a supplier and its struct is merged into this node's attributes before each record write.

```java
cluster.addAttributeContributor( () -> Struct.of( Key.of( "queueDepth" ), queue.size() ) );
```

A contributor that throws is logged and skipped. The other contributors still run and the record is still written, so no contributor can make a node look dead.

### Announce: listen for `onClusterNodeAttributes`

On every heartbeat, BoxLang announces `onClusterNodeAttributes` before it writes the record. The data holds the `nodeId` and the live `attributes` struct, so an interceptor can add its own keys.

```js
// Interceptor: add this node's data when the announcement fires
function onClusterNodeAttributes( data ) {
    data.attributes[ "region" ] = "us-east"
}
```

See [Interceptors](https://boxlang.ortusbooks.com/boxlang-framework/interceptors.md) for how to register one.

## 🔭 Reading the Fleet

The peer view is **lazy**. Nothing polls peers on a timer, so a deployment where nothing asks for them does no peer reads at all. A stale snapshot triggers exactly one refresh no matter how many callers ask, and callers wait for that refresh instead of receiving a half-populated snapshot.

| Method                                      | Returns                                                                                                                    |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `getNodes()`                                | Every known node, including this one, as a struct of `nodeId` to record.                                                   |
| `getPeers()`                                | Every known node **except** this one.                                                                                      |
| `getNode( nodeId )`                         | One record. This node is answered from memory and never read back from the cache. An unknown node returns an empty struct. |
| `getNodeAttribute( nodeId, path, default )` | One value by dotted path, such as `attributes.perf.cpu.load`, or the default.                                              |
| `getNodeNavigator( nodeId )`                | The same record, wrapped in a navigator for chaining.                                                                      |
| `getClusterReport()`                        | A diagnostic view of the node id, cluster name, cache, mode, attributes and known nodes.                                   |

`getNodes()` and `getPeers()` also take a freshness window in milliseconds. The default is one heartbeat, and `0` forces a re-read.

```java
Object load = cluster.getNodeAttribute( "web-2", "attributes.perf.cpu.load", 0.0 );
```

`getNodeAttribute` is forgiving by design:

* **The default shapes the result.** When the default is a number, the value is read as a number. A contributor that stored a non-numeric value yields your default instead of an exception, so one feature's bad value cannot break another's read.
* **Stale attributes are ignored.** When a node is alive but its attributes are older than three heartbeats, any path under `attributes` returns your default, because that data is no longer trustworthy.

## 🧱 Design Principles

* **It never decides anything.** There is no leader election, no "who is busiest" and no claim arbitration. Every semantic judgment belongs to the feature built on top. That is what keeps the service small and stops it from growing into a distributed consensus framework.
* **Best effort coordination.** The shared cache offers no atomic create, so features built on it must tolerate a narrow window where two nodes act at once. Clustered scheduled tasks say so plainly: make clustered jobs idempotent.
* **One root in the cache.** Everything lives under `bxcluster:{cluster}:`, and each feature owns its own segment beneath it. The cluster name is the second segment of every key, so two clusters can share one physical cache and stay separate. See the [cache key layout](https://boxlang.ortusbooks.com/boxlang-framework/asynchronous-programming/clustered-scheduled-tasks.md#cache-key-layout).
* **No cost when unused.** A node that is not in a cluster does no coordination work, and an unclustered task adds no cache traffic.

## 🧩 What Is Built on It

| Feature                                                                                                                             | Status                                                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [Clustered Scheduled Tasks](https://boxlang.ortusbooks.com/boxlang-framework/asynchronous-programming/clustered-scheduled-tasks.md) | Ships in 1.20.0. Each occurrence of a task runs on one node, shared out by load, with failover and a full run history. |
| Cache invalidation, distributed locking, per-node health aggregation                                                                | Design intent. The service is built so that features like these can sit on it. None of them ship on it in 1.20.0.      |

## 🧰 Troubleshooting

| Symptom                                        | Likely cause                                                                                                          |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Nodes do not see each other                    | `cluster.name` differs, or `cluster.cacheName` points at a cache that is local to each JVM.                           |
| A node drops out of `getNodes()`               | It missed about three heartbeats. Check the node, its network path to the shared cache, and `heartbeatSeconds`.       |
| `getNodeAttribute` keeps returning the default | The attributes are older than three heartbeats, the path is wrong, or the value cannot be read as the default's type. |
| Startup logs a coordination cache error        | The cache could not write, read back and remove a test value. Check the cache configuration.                          |

## 📚 Related

* [Cluster configuration](https://boxlang.ortusbooks.com/getting-started/configuration/cluster.md)
* [Clustered Scheduled Tasks](https://boxlang.ortusbooks.com/boxlang-framework/asynchronous-programming/clustered-scheduled-tasks.md)
* [Scheduled Tasks](https://boxlang.ortusbooks.com/boxlang-framework/asynchronous-programming/scheduled-tasks.md)
* [Caches](https://boxlang.ortusbooks.com/getting-started/configuration/caches.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://boxlang.ortusbooks.com/boxlang-framework/clustering-services.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
