Matrix is the gold standard for decentralized, end-to-end encrypted communication, powering government messaging systems, open-source communities, and privacy-focused organizations worldwide. For individual developers, the appeal is often more personal: bridging fragmented chat networks into a single inbox, or ensuring conversation history lives on infrastructure you control. But traditionally, running a Matrix homeserver has meant accepting a heavy operational burden.

A developer has successfully ported a Matrix homeserver to Cloudflare Workers, creating a serverless architecture where operations disappear, costs scale to zero when idle, and every connection is protected by post-quantum cryptography by default. This proof of concept demonstrates the future of decentralized protocols.

The Traditional Matrix Tax

Traditionally, operating a Matrix homeserver meant provisioning virtual private servers, tuning PostgreSQL for heavy write loads, managing Redis for caching, configuring reverse proxies, and handling TLS certificate rotation. It's a stateful, heavy system that demands constant feeding of time and money, whether you're using it heavily or minimally.

Matrix operates as a decentralized, eventually consistent state machine. Instead of a central server pushing updates, homeservers exchange signed JSON events over HTTP, using a conflict resolution algorithm to merge these streams into a unified view of room history.

This architecture provides powerful decentralization benefits, but the operational overhead has been substantial. The question became: could we eliminate that tax entirely?

From Synapse to Workers

The starting point was Synapse, the Python-based reference Matrix homeserver designed for traditional deployments. PostgreSQL for persistence, Redis for caching, filesystem for media.

Porting it to Workers meant questioning every storage assumption. The challenge was storage. Traditional homeservers assume strong consistency via a central SQL database. Cloudflare Durable Objects offers a powerful alternative, providing strong consistency and atomicity required for Matrix state resolution while allowing applications to run at the edge.

The core Matrix protocol logic—event authorization, room state resolution, cryptographic verification—was ported to TypeScript using the Hono framework. D1 replaces PostgreSQL, KV replaces Redis, R2 replaces the filesystem, and Durable Objects handle real-time coordination.

The Storage Mapping

The mapping worked out elegantly:

D1 stores everything needing to survive restarts and support queries: users, rooms, events, device keys. Over 25 tables covering the full Matrix data model. D1's SQLite foundation meant porting queries with minimal changes. Joins, indexes, and aggregations work as expected.

One hard lesson learned: D1's eventual consistency breaks foreign key constraints. A write to rooms might not be visible when a subsequent write to events checks the foreign key. All foreign keys were removed, with referential integrity enforced in application code.

KV handles ephemeral state. OAuth authorization codes live for 10 minutes, while refresh tokens last for sessions. KV's global distribution means OAuth flows work fast regardless of user location.

R2 handles media. Matrix media maps directly to R2—upload an image, get back a content-addressed URL, and egress is free.

Durable Objects provide atomicity. Some operations can't tolerate eventual consistency. When a client claims a one-time encryption key, that key must be atomically removed. If two clients claim the same key, encrypted session establishment fails. Durable Objects provide single-threaded, strongly consistent storage.

UserKeysObject handles E2EE key management, RoomObject manages real-time room events like typing indicators and read receipts, and UserSyncObject handles to-device message queues. The rest flows through D1.

From Monolith to Serverless

Moving to Cloudflare Workers brings several advantages:

Easy deployment: Traditional Matrix deployment requires server provisioning, PostgreSQL administration, Redis cluster management, TLS certificate renewal, load balancer configuration, monitoring infrastructure, and on-call rotations. With Workers, deployment is simply: wrangler deploy. Workers handles TLS, load balancing, DDoS protection, and global distribution.

Usage-based costs: Traditional homeservers cost money whether anyone is using them or not. Workers pricing is request-based—you pay when you're using it, but costs drop to near zero when everyone's asleep.

Lower latency globally: A traditional Matrix homeserver in us-east-1 adds 200ms+ latency for users in Asia or Europe. Workers run in 300+ locations worldwide. When a user in Tokyo sends a message, the Worker executes in Tokyo.

Built-in security: Matrix homeservers can be high-value targets. They handle encrypted communications, store message history, and authenticate users. Traditional deployments require careful hardening: firewall configuration, rate limiting, DDoS mitigation, WAF rules, IP reputation filtering. Workers provide all of this by default.

Post-Quantum Protection

Cloudflare deployed post-quantum hybrid key agreement across all TLS 1.3 connections in October 2022. Every connection to this Worker automatically negotiates X25519MLKEM768—a hybrid combining classical X25519 with ML-KEM, the post-quantum algorithm standardized by NIST.

Classical cryptography relies on mathematical problems that are hard for traditional computers but trivial for quantum computers running Shor's algorithm. ML-KEM is based on lattice problems that remain hard even for quantum computers. The hybrid approach means both algorithms must fail for the connection to be compromised.

Following a Message Through the System

Understanding where encryption happens matters for security architecture. When someone sends a message through this homeserver, here's the actual path:

The sender's client takes the plaintext message and encrypts it with Megolm—Matrix's end-to-end encryption. This encrypted payload then gets wrapped in TLS for transport. On Cloudflare, that TLS connection uses X25519MLKEM768, making it quantum-resistant.

The Worker terminates TLS, but what it receives is still encrypted—the Megolm ciphertext. We store that ciphertext in D1, index it by room and timestamp, and deliver it to recipients. But we never see the plaintext. The message exists only on the sender's device and the recipient's device.

When the recipient syncs, the process reverses. They receive the encrypted payload over another quantum-resistant TLS connection, then decrypt locally with their Megolm session keys.

Two Layers, Independent Protection

This provides two encryption layers operating independently:

The transport layer (TLS) protects data in transit. It's encrypted at the client and decrypted at the Cloudflare edge. With X25519MLKEM768, this layer is now post-quantum.

The application layer (Megolm E2EE) protects message content. It's encrypted on the sender's device and decrypted only on recipient devices. This uses classical Curve25519 cryptography.

Any Matrix homeserver operator—whether running Synapse on a VPS or this implementation on Workers—can see metadata: which rooms exist, who's in them, when messages were sent. But no one in the infrastructure chain can see message content, because the E2EE payload is encrypted on sender devices before it ever hits the network.

Traditional Deployments Would Require More

Achieving post-quantum TLS on a traditional Matrix deployment would require upgrading OpenSSL or BoringSSL to a version supporting ML-KEM, configuring cipher suite preferences correctly, testing client compatibility across all Matrix apps, monitoring for TLS negotiation failures, staying current as PQC standards evolve, and handling clients that don't support PQC gracefully.

With Workers, it's automatic. Chrome, Firefox, and Edge all support X25519MLKEM768. Mobile apps using platform TLS stacks inherit this support. The security posture improves as Cloudflare's PQC deployment expands—no action required.

Complete Implementation

The implementation supports the full Matrix E2EE stack: device keys, cross-signing keys, one-time keys, fallback keys, key backup, and dehydrated devices.

Modern Matrix clients use OAuth 2.0/OIDC instead of legacy password flows. A complete OAuth provider was implemented, with dynamic client registration, PKCE authorization, RS256-signed JWT tokens, token refresh with rotation, and standard OIDC discovery endpoints.

Point Element or any Matrix client at the domain, and it discovers everything automatically.

Sliding Sync for Mobile

Traditional Matrix sync transfers megabytes of data on initial connection, draining mobile battery and data plans. Sliding Sync lets clients request exactly what they need. Instead of downloading everything, clients get the 20 most recent rooms with minimal state. As users scroll, they request more ranges. The server tracks position and sends only deltas.

Combined with edge execution, mobile clients can connect and render their room list in under 500ms, even on slow networks.

The Comparison

For a homeserver serving a small team:

Traditional VPS: $20-50 monthly regardless of usage, 100-300ms global latency, hours to deploy, weekly maintenance, additional cost for DDoS protection, complex setup for post-quantum TLS.

Workers: <$1 monthly when idle, $3-10 when active, 20-50ms global latency, seconds to deploy, no maintenance, included DDoS protection, automatic post-quantum TLS.

The economics improve further at scale. Traditional deployments require capacity planning and over-provisioning. Workers scale automatically.

The Future of Decentralized Protocols

This started as an experiment: could Matrix run on Workers? It can—and the approach works for other stateful protocols too. By mapping traditional stateful components to Cloudflare's primitives—Postgres to D1, Redis to KV, mutexes to Durable Objects—complex applications don't need complex infrastructure.

This implementation strips away the operating system, database management, and network configuration, leaving only application logic and data. Workers offers sovereignty of owning your data, without the burden of owning infrastructure.

Source: Building a serverless, post-quantum Matrix homeserver - Cloudflare Blog