Run the data-heavy parts of a service where its data already lives.
Lagrange combines a distributed SQL database and a WebAssembly (WASI) service runtime. Every Lagrange node can hold database partitions and run service code near data.
Lagrange cluster
node A node B node C
+--------+ +--------+ +--------+
| data | | data | | data |
| P1* | | P1 | | P1 |
| P2 | | P2* | | P2 | <- replicas
| P3 | | P3 | | P3* |
| | | | | |
| WASM | | WASM | | WASM |
+--------+ +--------+ +--------+
* = that partition's leader replica
Instead of pulling large volumes of database rows across the network into
application servers, Lagrange runs partition-local functions (run()) on the
nodes holding the data, emits small numeric intermediate partials, and combines
them in a global reducer (reduce()).
Lagrange is designed for backend engineers, distributed systems teams, and data platform architects building services where network transfer between database and application tiers is the primary bottleneck.
Lagrange is a strong fit when an application:
- Reads large volumes of data to return a compact result (
data examined >> result returned). - Applies scoring, Bayesian ranking, feature extraction, filtering, or validation across partitions.
- Manually shards database queries in application code and manages fan-out and merging.
- Needs to deploy and test business logic in versioned application code (with
npm testand CI/CD) without installing database extensions or stored procedures.
Lagrange is not a good fit for:
- Pure API orchestration with negligible database queries.
- Queries where standard SQL is already optimal: When a query can be cleanly expressed as an indexed SQL query or a standard
SELECT ... GROUP BY ... ORDER BY ... LIMIT K, the database engine already computes the result and top-N heap locally and returns only the final rows. Moving such queries into WASM functions adds complexity without benefit. Measure against plain SQL first. - Complex multi-table transactions requiring distributed cross-partition locking snapshots.
Lagrange is experimental alpha software under active development:
- Run
npm view lagrange-server versionto see the published npm version. Release notes and tagged sources are available on the GitHub releases page. - Comparison Integrity: No comparative performance result is currently published. Every comparative result published before 2026-11-01 was withdrawn after an evidence audit (timeouts counted as successes, non-canonical workloads, constant phase/byte values, synthesised quantiles); the records are retained as forensic evidence behind an append-only invalidation ledger. The comparative benchmark overview shows the admission status of every advertised claim.
- Integrated Storage: Lagrange provides its own partitioned SQLite and Raft consensus storage layer; it is not a compute proxy installed on top of existing external databases.
The current public interface is intentionally focused and fails closed:
- Supported Language: JavaScript is the supported code-first language today (compiled to WASI via ComponentizeJS). Future execution provider policies (including OCI containers) are detailed in Minimal Deployment Surface.
- SQL Selectors: Distributed operations require a literal single-table
SELECTstatement fixed at deployment. No dynamic string interpolation is permitted. - Shard Input Bounds: Each partition shard evaluates up to a default limit of 4,096 rows per batch.
- Partials: Emitted partial values must be finite numbers (
Number.isFinite(value)). At most 64 emits per shard and 1,024 coordinated partials per invocation are permitted under shard-disjoint keys. - PostgreSQL Compatibility: Lagrange speaks a subset of the PostgreSQL wire protocol for client connectivity, not drop-in PostgreSQL. Secondary indexes, multi-statement scripts, and user-table CDC event streaming (
CDC_EVENT_STREAM_DISABLED) are unsupported. - Network and Resilience: Inter-node transport assumes a trusted private network. Supported rolling upgrades and automated backup/PITR are not yet supported product contracts.
See Current Capabilities and Limitations for full details.
With Node.js 22.12 or newer, run these commands in an empty directory to install the published package and check the node configuration.
npm init -y
npm install lagrange-server
npx lagrange --version
NODE_HOST_ID=demo-host npx lagrange --dry-run --data-dir ./lagrange-dataThe dry run prints Dry run completed. The installed package supplies both the lagrange and lagrange-admin commands.
To start one node in the foreground, use a fresh data directory and leave ports 8080 (REST), 8081 (admin WebSocket), and 8082 (transport WebSocket) available. For this single-node evaluation, explicitly request one replica for newly created table partitions. The default is three replicas. A table with one replica has no redundant copy. Run the installed binary from the same directory:
PARTITION_DEFAULT_REPLICA_COUNT=1 NODE_HOST_ID=demo-host ./node_modules/.bin/lagrange --data-dir ./single-node-dataIn a second terminal, check readiness:
curl -fsS http://127.0.0.1:8080/readyzAfter HTTP 200 with "ready":true, open a Node.js 22 REPL in the second terminal with node. Connect to the admin SQL stream and wait for the initial cache_dump before submitting statements:
const socket = (() => {
const ws = new WebSocket('ws://127.0.0.1:8081/api/admin/stream');
ws.onmessage = ({data}) => {
const message = JSON.parse(data);
if (message.type === 'cache_dump') console.log('Connected to', message.nodeId);
if (['query_result', 'error'].includes(message.type)) console.log(message);
};
return ws;
})();
const query = sql => socket.send(JSON.stringify({type: 'query', queryId: crypto.randomUUID(), sql}));Run each line after the previous query succeeds:
query('CREATE TABLE npm_smoke (id INTEGER PRIMARY KEY, value TEXT)');
query("INSERT INTO npm_smoke (id, value) VALUES (1, 'hello')");
query('SELECT id, value FROM npm_smoke WHERE id = 1');The SELECT should return one row with id: 1 and value: 'hello'. Close the client with socket.close(). The admin API reference describes the request and result envelopes.
To shut down cleanly, press Ctrl-C once (SIGINT) in the foreground terminal and wait for the command to exit. The node keeps its data in ./single-node-data.
In a separate directory, clone the repository and run the demonstration.
git clone https://github.com/psvensson/lagrange
cd lagrange
npm install
npm run demo:account-summaryThe demo:
- Compiles
examples/call-binding-account-summary/lagrange.service.jsinto a genuine WASI component; - Starts an ephemeral node, creates a table, and splits it into two partitions;
- Deploys the service over PostgreSQL-wire lifecycle SQL;
- Invokes the HTTP endpoint
POST /amounts/summary; - Executes
run()locally across partition leaders (emitting 8 numeric partials with 0 raw rows transferred across the network); and - Reduces the partials into a single JSON summary report.
Create a new service project using the CLI:
npx lagrange service init my-service
cd my-service
npm test
npm run buildThe build script compiles your source into .lagrange/component.wasm and generates deterministic deployment records under .lagrange/deployment/.
To deploy to a running cluster:
# 1. Publish into the replicated ArtifactPayloadStore (returns <package-id>)
npx lagrange service publish .
# 2. Deploy by registered immutable identity (no local files needed)
npx lagrange service deploy --package-id <package-id> --idempotency-key deploy-key-v1See First Hour With Lagrange for the complete walkthrough.
If you have an existing Kubernetes cluster or cloud VMs:
- Kubernetes (Helm): Deploy via
helm install lagrange charts/lagrange-node --set image.tag=0.3.3 --set joiners.replicas=2and deploy WASI services over SQL without pod volume mounts. - Cloud Benchmarks: Run Scenario A (contended OLTP), Scenario B (locality/RTT), Scenario C (freshness), and MovieLens against your own GCP project or lab servers via
npm run distributed:gcpor--gcp-template.
See Kubernetes Deployment and Cloud Benchmarks.
Lagrange exposes health probes and diagnostic streams on dedicated ports:
- HTTP REST / Ingress (
REST_API_PORT=8080):curl -fsS http://127.0.0.1:8080/livez- Node process liveness.curl -fsS http://127.0.0.1:8080/startupz- Core service startup and schema initialization.curl -fsS http://127.0.0.1:8080/readyz- Cluster quorum readiness and request acceptance.
- Admin WebSocket (
ADMIN_WS_PORT=8081):- Diagnostic stream at
ws://127.0.0.1:8081/api/admin/streamfor real-time events, cluster status, and CDC logs.
- Diagnostic stream at
- Transport WebSocket (
TRANSPORT_WS_PORT=8082):- Inter-node Raft consensus and replica synchronization.
- PostgreSQL Wire Protocol (
PGPORT=5432):- Standard SQL ingress and lifecycle management (
SHOW SERVICE '<name>').
- Standard SQL ingress and lifecycle management (
For detailed authoring rules, see JavaScript Service Reference.
- First Hour With Lagrange - Complete step-by-step developer walkthrough
- Kubernetes and Cloud Benchmarks - Helm chart guide, credential config, and cloud benchmark matrix
- JavaScript Service Reference - Authoring API, typings, and limits
- Comparative benchmark overview - admission status of every advertised comparative claim; earlier results are withdrawn and kept as forensic history
- Rewrite A Hot Path For Lagrange - MovieLens top-N three-baseline tutorial
- The Lagrange Native Programming Model - Handlers,
run(), andreduce() - Execution Semantics - Placement, retries, and visibility guarantees
- Evaluating Lagrange - Workload evaluation checklist
- Migration and Adoption - Introducing Lagrange into an architecture
- Security - Trust model and capability boundaries
- Architecture Index - Cluster internals and system model
examples/call-binding-account-summary/- Flagship code-first service and demonstrationexamples/service-data-affinity/- 5-node MovieLens Top-N affinity studydocs/- Tutorials, guides, and reference manualssrc/authoring/andsrc/service/- Guest-safe authoring API and WASI compilersrc/runtime/,src/query/, andsrc/raft/- Storage engine, distributed query planner, and consensusarchitecture/- System model, contract definitions, and invariants
Lagrange is licensed under AGPL-3.0-only. See LICENSE.
The repository source is public; external pull requests are currently closed. Bug reports and feedback are welcome at CONTRIBUTING.md. Agents working on the repository begin at AGENTS.md.