* This publish was up to date at 11:45 a.m. Pacific time to make clear that the use case described here’s a proof of idea and a private mission. Some sections have been up to date for readability.
Matrix is the gold customary for decentralized, end-to-end encrypted communication. It powers authorities messaging methods, open-source communities, and privacy-focused organizations worldwide.
For the person developer, nonetheless, the enchantment is commonly nearer to residence: bridging fragmented chat networks (like Discord and Slack) right into a single inbox, or just making certain your dialog historical past lives on infrastructure you management. Functionally, Matrix operates as a decentralized, ultimately constant state machine. As an alternative of a central server pushing updates, homeservers trade signed JSON occasions over HTTP, utilizing a battle decision algorithm to merge these streams right into a unified view of the room’s historical past.
However there’s a “tax” to working it. Historically, working a Matrix homeserver has meant accepting a heavy operational burden. You must provision digital non-public servers (VPS), tune PostgreSQL for heavy write masses, handle Redis for caching, configure reverse proxies, and deal with rotation for TLS certificates. It’s a stateful, heavy beast that calls for to be fed money and time, whether or not you’re utilizing it rather a lot or slightly.
We wished to see if we might eradicate that tax fully.
Spoiler: We might. On this publish, we’ll clarify how we ported a Matrix homeserver to Cloudflare Staff. The ensuing proof of idea is a serverless structure the place operations disappear, prices scale to zero when idle, and each connection is protected by post-quantum cryptography by default. You may view the supply code and deploy your individual occasion instantly from Github.
Our place to begin was Synapse, the Python-based reference Matrix homeserver designed for conventional deployments. PostgreSQL for persistence, Redis for caching, filesystem for media.
Porting it to Staff meant questioning each storage assumption we’d taken without any consideration.
The problem was storage. Conventional homeservers assume robust consistency by way of a central SQL database. Cloudflare Sturdy Objects affords a robust different. This primitive provides us the robust consistency and atomicity required for Matrix state decision, whereas nonetheless permitting the applying to run on the edge.
We ported the core Matrix protocol logic — occasion authorization, room state decision, cryptographic verification — in TypeScript utilizing the Hono framework. D1 replaces PostgreSQL, KV replaces Redis, R2 replaces the filesystem, and Sturdy Objects deal with real-time coordination.
Right here’s how the mapping labored out:
From monolith to serverless
Transferring to Cloudflare Staff brings a number of benefits for a developer: easy deployment, decrease prices, low latency, and built-in safety.
Straightforward deployment: A conventional Matrix deployment requires server provisioning, PostgreSQL administration, Redis cluster administration, TLS certificates renewal, load balancer configuration, monitoring infrastructure, and on-call rotations.
With Staff, deployment is just: wrangler deploy. Staff handles TLS, load balancing, DDoS safety, and international distribution.
Utilization-based prices: Conventional homeservers price cash whether or not anybody is utilizing them or not. Staff pricing is request-based, so that you pay whenever you’re utilizing it, however prices drop to close zero when everybody’s asleep.
Decrease latency globally: A conventional Matrix homeserver in us-east-1 provides 200ms+ latency for customers in Asia or Europe. Staff, in the meantime, run in 300+ areas worldwide. When a person in Tokyo sends a message, the Employee executes in Tokyo.
Constructed-in safety: Matrix homeservers could be high-value targets: They deal with encrypted communications, retailer message historical past, and authenticate customers. Conventional deployments require cautious hardening: firewall configuration, price limiting, DDoS mitigation, WAF guidelines, IP status filtering.
Staff present all of this by default.
Submit-quantum safety
Cloudflare deployed post-quantum hybrid key settlement throughout all TLS 1.3 connections in October 2022. Each connection to our Employee mechanically negotiates X25519MLKEM768 — a hybrid combining classical X25519 with ML-KEM, the post-quantum algorithm standardized by NIST.
Classical cryptography depends on mathematical issues which are onerous for conventional computer systems however trivial for quantum computer systems working Shor’s algorithm. ML-KEM is predicated on lattice issues that stay onerous even for quantum computer systems. The hybrid strategy means each algorithms should fail for the connection to be compromised.
Following a message by the system
Understanding the place encryption occurs issues for safety structure. When somebody sends a message by our homeserver, right here’s the precise path:
The sender’s shopper takes the plaintext message and encrypts it with Megolm — Matrix’s end-to-end encryption. This encrypted payload then will get wrapped in TLS for transport. On Cloudflare, that TLS connection makes use of X25519MLKEM768, making it quantum-resistant.
The Employee terminates TLS, however what it receives continues to be encrypted — the Megolm ciphertext. We retailer that ciphertext in D1, index it by room and timestamp, and ship it to recipients. However we by no means see the plaintext. The message “Hi there, world” exists solely on the sender’s system and the recipient’s system.
When the recipient syncs, the method reverses. They obtain the encrypted payload over one other quantum-resistant TLS connection, then decrypt regionally with their Megolm session keys.
Two layers, impartial safety
This protects by way of two encryption layers that function independently:
The transport layer (TLS) protects information in transit. It’s encrypted on the shopper and decrypted on the Cloudflare edge. With X25519MLKEM768, this layer is now post-quantum.
The software layer (Megolm E2EE) protects message content material. It’s encrypted on the sender’s system and decrypted solely on recipient gadgets. This makes use of classical Curve25519 cryptography.
Any Matrix homeserver operator — whether or not working Synapse on a VPS or this implementation on Staff — can see metadata: which rooms exist, who’s in them, when messages have been despatched. However nobody within the infrastructure chain can see the message content material, as a result of the E2EE payload is encrypted on sender gadgets earlier than it ever hits the community. Cloudflare terminates TLS and passes requests to your Employee, however each see solely Megolm ciphertext. Media in encrypted rooms is encrypted client-side earlier than add, and personal keys by no means go away person gadgets.
What conventional deployments would wish
Attaining post-quantum TLS on a standard Matrix deployment would require upgrading OpenSSL or BoringSSL to a model supporting ML-KEM, configuring cipher suite preferences appropriately, testing shopper compatibility throughout all Matrix apps, monitoring for TLS negotiation failures, staying present as PQC requirements evolve, and dealing with purchasers that don’t help PQC gracefully.
With Staff, it’s automated. Chrome, Firefox, and Edge all help X25519MLKEM768. Cellular apps utilizing platform TLS stacks inherit this help. The safety posture improves as Cloudflare’s PQC deployment expands — no motion required on our half.
The storage structure that made it work
The important thing perception from porting Tuwunel was that totally different information wants totally different consistency ensures. We use every Cloudflare primitive for what it does greatest.
D1 shops the whole lot that should survive restarts and help queries: customers, rooms, occasions, system keys. Over 25 tables masking the complete Matrix information mannequin.
CREATE TABLE occasions (
event_id TEXT PRIMARY KEY,
room_id TEXT NOT NULL,
sender TEXT NOT NULL,
event_type TEXT NOT NULL,
state_key TEXT,
content material TEXT NOT NULL,
origin_server_ts INTEGER NOT NULL,
depth INTEGER NOT NULL
);
D1’s SQLite basis meant we might port Tuwunel’s queries with minimal modifications. Joins, indexes, and aggregations work as anticipated.
We discovered one onerous lesson: D1’s eventual consistency breaks overseas key constraints. A write to rooms won’t be seen when a subsequent write to occasions checks the overseas key. We eliminated all overseas keys and implement referential integrity in software code.
OAuth authorization codes dwell for 10 minutes, whereas refresh tokens final for a session.
// Retailer OAuth code with 10-minute TTL
kv.put(&format!("oauth_code:{}", code), &token_data)?
.expiration_ttl(600)
.execute()
.await?;KV’s international distribution means OAuth flows work quick no matter the place customers are positioned.
Matrix media maps on to R2, so you may add a picture, get again a content-addressed URL – and egress is free.
Sturdy Objects for atomicity
Some operations can’t tolerate eventual consistency. When a shopper claims a one-time encryption key, that key have to be atomically eliminated. If two purchasers declare the identical key, encrypted session institution fails.
Sturdy Objects present single-threaded, strongly constant storage:
#[durable_object]
pub struct UserKeysObject {
state: State,
env: Env,
}
impl UserKeysObject {
async fn claim_otk(&self, algorithm: &str) -> OutcomeWe use UserKeysObject for E2EE key administration, RoomObject for real-time room occasions like typing indicators and browse receipts, and UserSyncObject for to-device message queues. The remaining flows by D1.
Full end-to-end encryption, full OAuth
Our implementation helps the complete Matrix E2EE stack: system keys, cross-signing keys, one-time keys, fallback keys, key backup, and dehydrated gadgets.
Trendy Matrix purchasers use OAuth 2.0/OIDC as an alternative of legacy password flows. We applied a whole OAuth supplier, with dynamic shopper registration, PKCE authorization, RS256-signed JWT tokens, token refresh with rotation, and customary OIDC discovery endpoints.
curl
{
"issuer": "
"authorization_endpoint": "
"token_endpoint": "
"jwks_uri": "
}
Level Component or any Matrix shopper on the area, and it discovers the whole lot mechanically.
Conventional Matrix sync transfers megabytes of information on preliminary connection, draining cell battery and information plans.
Sliding Sync lets purchasers request precisely what they want. As an alternative of downloading the whole lot, purchasers get the 20 most up-to-date rooms with minimal state. As customers scroll, they request extra ranges. The server tracks place and sends solely deltas.
Mixed with edge execution, cell purchasers can join and render their room checklist in beneath 500ms, even on gradual networks.
For a homeserver serving a small staff:
| Conventional (VPS) | Staff |
|---|---|---|
Month-to-month price (idle) | $20-50 | <$1 |
Month-to-month price (lively) | $20-50 | $3-10 |
World latency | 100-300ms | 20-50ms |
Time to deploy | Hours | Seconds |
Upkeep | Weekly | None |
DDoS safety | Further price | Included |
Submit-quantum TLS | Advanced setup | Computerized |
*Primarily based on public charges and metrics printed by DigitalOcean, AWS Lightsail, and Linode as of January 15, 2026.
The economics enhance additional at scale. Conventional deployments require capability planning and over-provisioning. Staff scale mechanically.
The way forward for decentralized protocols
We began this as an experiment: might Matrix run on Staff? It could actually—and the strategy can work for different stateful protocols, too.
By mapping conventional stateful elements to Cloudflare’s primitives — Postgres to D1, Redis to KV, mutexes to Sturdy Objects — we are able to see that complicated functions do not want complicated infrastructure. We stripped away the working system, the database administration, and the community configuration, leaving solely the applying logic and the information itself.
Staff affords the sovereignty of proudly owning your information, with out the burden of proudly owning the infrastructure.
I’ve been experimenting with the implementation and am excited for any contributions from others all in favour of this sort of service.
Able to construct highly effective, real-time functions on Staff? Get began with Cloudflare Staff and discover Sturdy Objects on your personal stateful edge functions. Be part of our Discord neighborhood to attach with different builders constructing on the edge.



