Why MLambda.Data?

The Problem with Traditional Databases

Every mainstream database — PostgreSQL, MySQL, MongoDB, Cassandra — shares the same foundational assumption: the database is a separate process that clients connect to over a network. This assumption, baked in during the 1970s-90s, forces every database into the same architectural constraints regardless of how modern the implementation is.

SQL Parsing: Four Transformations Before Touching Data

When you write SELECT * FROM users WHERE id = ?, here is what actually happens:

  1. Lexing — the raw text is tokenized into SQL tokens
  2. Parsing — tokens are assembled into an Abstract Syntax Tree (AST)
  3. Planning — the AST is transformed into a query execution plan, including cost estimation, index selection, and join ordering
  4. Execution — the plan is finally executed against the storage engine

Each step allocates memory, performs string comparisons, and introduces latency. For a simple point lookup by primary key, the first three steps are pure overhead. The database already knows exactly what you want — read one row by key — but it must parse your intent from text every single time.

Prepared statements cache the plan, but the client still serializes parameters into a wire protocol, and the server still deserializes them. The fundamental problem remains: text is a terrible interface for structured operations.

Connection Pool Complexity: Managing What Shouldn’t Exist

Traditional databases accept TCP connections. Each connection consumes server memory for buffers, authentication state, and transaction context. Servers can only handle a finite number (PostgreSQL defaults to 100). This creates a problem:

  • Applications need concurrency, but the database cannot handle concurrent connections efficiently
  • So we introduce connection pools (PgBouncer, HikariCP, etc.) — middleware that multiplexes application requests onto a smaller set of database connections
  • Now you have pool sizing decisions: too few connections and requests queue; too many and the database thrashes
  • Connection leaks become a class of bugs — forgot to return a connection to the pool? The pool drains, the application stalls, and you get paged at 3 AM
  • Health checks, timeout handling, retry logic, connection validation — all complexity that exists solely because the database speaks TCP

The actor model eliminates this entire category. An actor has a mailbox. Messages arrive. The actor processes them one at a time. There is no concept of a “connection” to leak, no pool to size, no timeout to configure.

Bolt-On Distribution: Sharding as an Afterthought

PostgreSQL was designed for a single machine. When you need to scale beyond one server, you have options — none of them clean:

  • Logical replication — asynchronous, eventual consistency, manual failover
  • Citus — a sharding extension that requires you to choose distribution keys and hope you got it right
  • Patroni — a separate process managing HA with etcd/ZooKeeper, adding operational complexity

Cassandra was designed for distribution, but it solves it with a custom gossip protocol, a custom partitioner, a custom consistency coordinator — all built from scratch because the storage engine has no native concept of distribution.

MongoDB’s approach is similar: a separate mongos router, config servers, and shard servers, each a different process with different failure modes.

In MLambda.Data, the actor framework IS the distribution layer. The same routing mechanism that delivers a message to a local actor delivers it to a remote actor. Scaling means spawning more actors — on the same node or across nodes. The framework handles discovery, routing, and failover.

Impedance Mismatch: Why ORMs Exist

Object-relational mappers exist because databases and applications speak different languages: the application has values with fields, the database rows with columns, and between them an ORM translates method calls into SQL text and result sets back into objects.

In MLambda.Data an entity’s instance Entity is its mapping: the table (columns, keys, indexes, replication), how a value becomes columns, and its key. A repository takes and gives back the entity type. There is no query language to translate into.

Wire Protocol Overhead: Serialization Tax

Every traditional database interaction crosses four serialization boundaries:

Application → serialize → send → receive → deserialize → process →
serialize → send → receive → deserialize → Application

Inside an MLambda.Data node, a request is a value in an actor’s mailbox: nothing is serialized. Between nodes the actor transport writes it once, as a compact binary document.


The Actor Model Solution

Values replace SQL

Instead of:

INSERT INTO users (id, name, email) VALUES ('abc', 'Alice', '[email protected]')

a program saves an entity:

save users (User "abc" "Alice" (Just "[email protected]") 30)

or, below the ORM, asks the engine with a message:

ask engine (\r -> EngineWrite "app" "users" key columns stamp r)

The request is a value of an Aleph data type: the compiler checks it, and nothing in it is parsed, so it cannot be injected.

Mailboxes replace connections

An actor handles one message at a time from its mailbox:

  • natural backpressure: if the actor is busy, messages wait in its mailbox (bounded mailboxes make senders wait);
  • no locks: one message at a time leaves no data races;
  • no connections: there is nothing to open, close, pool or leak;
  • no thread pools to tune: actors are fibers on the runtime’s scheduler.

The framework is the cluster

Database Distribution
PostgreSQL Streaming replication + external HA (Patroni)
Cassandra Custom gossip + partitioner + coordinator
MongoDB mongos router + config servers + shards
CockroachDB Raft per range
MLambda.Data MLambda.Actor’s cluster: gossip membership, routes, and a ring of replicas the coordinator asks

The same routing that delivers a message to a local actor delivers it to a remote one.

One language, one mapping

instance Entity User where
  mapping = mappedTo "app"
    (hashIndex "ix_email" ["email"]
      (clusteringKey ["created"]
        (partitionKey ["id"]
          (replicas 3 (...)))))
  ...

The mapping is at once the table’s schema, its indexes, its keys and its replication, checked when the repository opens. There are no migration files: a schema change is an evolution the registry accepts only if old rows still read.


Comparison Table

Aspect PostgreSQL Cassandra MongoDB MLambda.Data
Query interface SQL text CQL text BSON/JSON Typed values (specifications)
Connection model TCP pool TCP pool TCP pool Actor mailbox
Distribution Bolt-on replication DHT ring Sharding Actor framework + ring
Consistency ACID (single node) Tunable Eventual Tunable per request (One / Quorum / All)
Schema Rigid DDL Rigid CQL Schemaless Entity mappings, checked; evolution that keeps old rows readable
Recovery WAL replay Commitlog Oplog WAL + snapshots + manifest; read repair across replicas
Parsing overhead SQL parse + plan CQL parse BSON decode None
Serialization hops 4 4 4 0 (local), 1 each way (remote)
Monitoring pg_stat + extensions JMX / nodetool mongotop / mongostat Live channels: metrics, ring, cluster, alerts, compaction
Failure handling Process restart Hinted handoff Replica set election Guardian supervision by failure kind + compaction breaker
Index types B-tree, Hash, GIN, GiST SAI, SASI Single, compound, text B-tree, hash, bloom, inverted
Joins Server-side SQL None (denormalize) $lookup Hash join in the engine
Compaction VACUUM Size/Leveled/TWCS WiredTiger Size-tiered, paced by the disk’s load

Why This Matters: Concrete Benefits

1. No query injection

Injection exists because databases accept text that mixes code and data. A request here is a value:

-- This is the query. There is no text to inject into.
find users (B.bytesFromString userId)

The key is bytes; nothing in the request is parsed.

2. No connection leaks

There are no connections. A repository sends messages to the engine actor; there is nothing to acquire, return or leak.

case openRepository engine of
  Right users -> case save users user of
    _ -> find users key

3. No impedance mismatch

  • The entity’s instance Entity defines its table, keys and indexes.
  • A repository takes and gives back the entity type.
  • Specifications are values: filters joined by and, or and not.
  • Joins run inside the engine, on the tables’ own rows.

4. Scaling

Adding capacity to a traditional database means configuring replication, choosing shard keys or rebalancing by hand. Here a node joins the ring (DATA_NODES, SEEDS), and the ring gives it its share of the keys: about a quarter when a fourth node joins three.

5. Self-healing recovery

  1. Guardians restart the failing part by the failure’s kind.
  2. The log, the snapshot and the manifest bring a restarted table back to its last acknowledged write.
  3. Read repair brings a replica that fell behind up to date on the next quorum read.

The Docker topologies stop every server and start them again on their volumes, and check the data is still there.

6. Operational simplicity

Operation PostgreSQL MLambda.Data
Schema change Migration SQL, ALTER TABLE An evolution the registry checks against old rows
Add an index CREATE INDEX CONCURRENTLY Add it to the mapping
Change replication Reconfigure streaming replication replicas n in the mapping
Monitor pg_stat_statements, an exporter The live channels (/ws/metrics, …)
Deploy Packages, configuration files One static binary in an Alpine image, configured by its environment