Skip to content
psvenssonPublic

Latest commit

 

History

6,298 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lagrange

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()).


Audience and Workload Fit

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.

Workload Fit

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 test and CI/CD) without installing database extensions or stored procedures.

Non-Fit and When Plain SQL Is Better

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.

Bounded Evaluation Commitment and Version Truth

Lagrange is experimental alpha software under active development:

  • Run npm view lagrange-server version to 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.

Immediate Capabilities and Limits

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 SELECT statement 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.


Try it

Install from npm

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-data

The 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-data

In a second terminal, check readiness:

curl -fsS http://127.0.0.1:8080/readyz

After 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.

Run the account-summary demonstration from source

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-summary

The demo:

  1. Compiles examples/call-binding-account-summary/lagrange.service.js into a genuine WASI component;
  2. Starts an ephemeral node, creates a table, and splits it into two partitions;
  3. Deploys the service over PostgreSQL-wire lifecycle SQL;
  4. Invokes the HTTP endpoint POST /amounts/summary;
  5. Executes run() locally across partition leaders (emitting 8 numeric partials with 0 raw rows transferred across the network); and
  6. Reduces the partials into a single JSON summary report.

Scaffold Your Own Service

Create a new service project using the CLI:

npx lagrange service init my-service
cd my-service
npm test
npm run build

The 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-v1

See First Hour With Lagrange for the complete walkthrough.

Deploy on Kubernetes and Run Cloud Benchmarks

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=2 and 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:gcp or --gcp-template.

See Kubernetes Deployment and Cloud Benchmarks.


Troubleshooting and Diagnostics

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/stream for real-time events, cluster status, and CDC logs.
  • 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>').

For detailed authoring rules, see JavaScript Service Reference.


Read Next


Repository Layout

  • examples/call-binding-account-summary/ - Flagship code-first service and demonstration
  • examples/service-data-affinity/ - 5-node MovieLens Top-N affinity study
  • docs/ - Tutorials, guides, and reference manuals
  • src/authoring/ and src/service/ - Guest-safe authoring API and WASI compiler
  • src/runtime/, src/query/, and src/raft/ - Storage engine, distributed query planner, and consensus
  • architecture/ - System model, contract definitions, and invariants

License and Contributions

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.