Matrix serves as a leading platform for decentralized, end-to-end encrypted communication, utilized by government messaging systems, open-source communities, and privacy-focused organizations globally.
For individual developers, its appeal often lies in connecting disparate chat networks (such as Discord and Slack) into a unified inbox, or maintaining control over conversation history by hosting it on personal infrastructure. Matrix functions as a decentralized, eventually consistent state machine. Homeservers exchange signed JSON events via HTTP, employing a conflict resolution algorithm to combine these event streams into a coherent room history.
However, running a Matrix homeserver traditionally involves significant operational overhead. This includes provisioning virtual private servers (VPS), optimizing PostgreSQL for intensive write operations, managing Redis for caching, configuring reverse proxies, and handling TLS certificate rotations. It represents a stateful, resource-intensive system requiring ongoing time and financial investment, regardless of usage levels.
The goal was to explore whether this operational burden could be completely removed.
This proved achievable. This post details the process of porting a Matrix homeserver to Cloudflare Workers. The resulting proof of concept demonstrates a serverless architecture that eliminates operational tasks, reduces costs to near zero during idle periods, and secures every connection with post-quantum cryptography by default. The source code is available, allowing direct deployment of an instance from Github.
From Synapse to Workers
The project began with Synapse, the Python-based reference Matrix homeserver traditionally deployed with PostgreSQL for persistence, Redis for caching, and a filesystem for media.
Porting Synapse to Workers necessitated re-evaluating all conventional storage assumptions.
Storage presented a key challenge. Traditional homeservers rely on strong consistency provided by a central SQL database. Cloudflare Durable Objects provides a robust alternative, offering the strong consistency and atomicity essential for Matrix state resolution, while enabling the application to operate at the edge.
The core Matrix protocol logic, including event authorization, room state resolution, and cryptographic verification, was ported to TypeScript using the Hono framework. D1 now serves as the replacement for PostgreSQL, KV for Redis, R2 for the filesystem, and Durable Objects manage real-time coordination.
From monolith to serverless
Transitioning to Cloudflare Workers offers developers multiple benefits: simplified deployment, reduced costs, low latency, and integrated security.
Easy deployment: A conventional Matrix deployment necessitates server provisioning, PostgreSQL administration, Redis cluster management, TLS certificate renewal, load balancer configuration, monitoring infrastructure, and on-call rotations.
With Workers, deployment is streamlined to a single command: wrangler deploy. Workers automatically manages TLS, load balancing, DDoS protection, and global distribution.
Usage-based costs: Traditional homeservers incur expenses regardless of active use. Workers pricing is based on requests, meaning costs are incurred only during active usage and approach zero during idle periods.
Lower latency globally: A conventional Matrix homeserver located in us-east-1 can introduce over 200ms of latency for users in Asia or Europe. In contrast, Workers operate in over 300 locations globally. For instance, when a user in Tokyo sends a message, the Worker executes in Tokyo.
Built-in security: Matrix homeservers are often high-value targets due to their handling of encrypted communications, storage of message history, and user authentication. Traditional deployments demand meticulous hardening, including firewall configuration, rate limiting, DDoS mitigation, WAF rules, and IP reputation filtering.
Workers inherently provide these security features.
Post-quantum protection
Cloudflare implemented post-quantum hybrid key agreement for all TLS 1.3 connections in October 2022. Each connection to a Worker automatically negotiates X25519MLKEM768, a hybrid approach that combines classical X25519 with ML-KEM, the post-quantum algorithm standardized by NIST.
Classical cryptography depends on mathematical problems that are challenging for traditional computers but easily solvable by quantum computers utilizing Shor’s algorithm. ML-KEM, conversely, is founded on lattice problems that maintain their difficulty even for quantum computers. This hybrid strategy ensures that both algorithms must be compromised for a connection to be breached.
Following a message through the system
Understanding the points of encryption is crucial for security architecture. When a message is sent through this homeserver, the process unfolds as follows:
The sender’s client encrypts the plaintext message using Megolm, Matrix’s end-to-end encryption. This encrypted payload is then encapsulated within TLS for transport. On Cloudflare, the TLS connection employs X25519MLKEM768, providing quantum resistance.
The Worker terminates TLS, yet the data it receives remains encrypted as Megolm ciphertext. This ciphertext is stored in D1, indexed by room and timestamp, and then delivered to recipients. The plaintext message is never exposed to the homeserver. A message “Hello, world” exists solely on the sender’s and recipient’s devices.
Upon recipient synchronization, the process reverses. The recipient obtains the encrypted payload via another quantum-resistant TLS connection and then decrypts it locally using their Megolm session keys.
Two layers, independent protection
Protection is provided through two independent encryption layers:
The transport layer (TLS) secures data during transit. Encryption occurs at the client and decryption at the Cloudflare edge. With X25519MLKEM768, this layer achieves post-quantum security.
The application layer (Megolm E2EE) safeguards message content. Encryption happens on the sender’s device and decryption exclusively on recipient devices, utilizing classical Curve25519 cryptography.
Who sees what
Any Matrix homeserver operator, whether using Synapse on a VPS or this Workers implementation, has access to metadata such as existing rooms, participants, and message timestamps. However, no entity in the infrastructure chain can view message content, as the E2EE payload is encrypted on sender devices prior to network transmission. Cloudflare terminates TLS and forwards requests to the Worker, but both only encounter Megolm ciphertext. Media within encrypted rooms is client-side encrypted before upload, and private keys remain exclusively on user devices.
What traditional deployments would need
Implementing post-quantum TLS in a traditional Matrix deployment would involve upgrading OpenSSL or BoringSSL to a ML-KEM-compatible version, correctly configuring cipher suite preferences, testing client compatibility across all Matrix applications, monitoring for TLS negotiation failures, keeping up with evolving PQC standards, and gracefully managing clients that lack PQC support.
With Workers, this process is automatic. Chrome, Firefox, and Edge browsers all support X25519MLKEM768. Mobile applications leveraging platform TLS stacks inherently gain this support. The security posture automatically enhances as Cloudflare’s PQC deployment expands, requiring no manual intervention.
The storage architecture that made it work
A key insight from this porting effort was recognizing that various data types require distinct consistency guarantees. Each Cloudflare primitive is utilized for its optimal function.
D1 for the data model
D1 serves as the storage for all data requiring persistence across restarts and query support, including users, rooms, events, and device keys. This encompasses over 25 tables covering the complete Matrix data model.
CREATE TABLE events (
event_id TEXT PRIMARY KEY,
room_id TEXT NOT NULL,
sender TEXT NOT NULL,
event_type TEXT NOT NULL,
state_key TEXT,
content TEXT NOT NULL,
origin_server_ts INTEGER NOT NULL,
depth INTEGER NOT NULL
);
D1’s SQLite foundation allowed for porting queries with minimal modifications. Joins, indexes, and aggregations function as anticipated.
A significant lesson learned was that D1’s eventual consistency can disrupt foreign key constraints. For example, a write to rooms might not be immediately visible when a subsequent write to events attempts to check a foreign key. Consequently, all foreign keys were removed, and referential integrity is now enforced within the application code.
KV for ephemeral state
OAuth authorization codes have a 10-minute lifespan, whereas refresh tokens persist for the duration of a session.
// Store OAuth code with 10-minute TTL
kv.put(&format!("oauth_code:{}", code), &token_data)?
.expiration_ttl(600)
.execute()
.await?;
KV’s global distribution ensures rapid OAuth flows, irrespective of user location.
R2 for media
Matrix media directly integrates with R2, enabling image uploads that return a content-addressed URL, with free egress.
Durable Objects for atomicity
Certain operations cannot tolerate eventual consistency. For instance, when a client claims a one-time encryption key, that key must be atomically removed. If multiple clients attempt to claim the same key, encrypted session establishment will fail.
Durable Objects offer single-threaded, strongly consistent storage:
#[durable_object]
pub struct UserKeysObject {
state: State,
env: Env,
}
impl UserKeysObject {
async fn claim_otk(&self, algorithm: &str) -> Result<Option<Key>> {
// Atomic within single DO - no race conditions possible
let mut keys: Vec<Key> = self.state.storage()
.get("one_time_keys")
.await
.ok()
.flatten()
.unwrap_or_default();
if let Some(idx) = keys.iter().position(|k| k.algorithm == algorithm) {
let key = keys.remove(idx);
self.state.storage().put("one_time_keys", &keys).await?;
return Ok(Some(key));
}
Ok(None)
}
}
UserKeysObject is utilized for E2EE key management, RoomObject for real-time room events such as typing indicators and read receipts, and UserSyncObject for to-device message queues. All other data flows through D1.
Complete end-to-end encryption, complete OAuth
This implementation supports the entire Matrix E2EE stack, including device keys, cross-signing keys, one-time keys, fallback keys, key backup, and dehydrated devices.
Modern Matrix clients leverage OAuth 2.0/OIDC in place of older password flows. A comprehensive OAuth provider was implemented, featuring dynamic client registration, PKCE authorization, RS256-signed JWT tokens, token refresh with rotation, and standard OIDC discovery endpoints.
curl https://matrix.example.com/.well-known/openid-configuration
{
"issuer": "https://matrix.example.com",
"authorization_endpoint": "https://matrix.example.com/oauth/authorize",
"token_endpoint": "https://matrix.example.com/oauth/token",
"jwks_uri": "https://matrix.example.com/.well-known/jwks.json"
}
By pointing Element or any Matrix client to the domain, automatic discovery of all necessary configurations occurs.
Sliding Sync for mobile
Conventional Matrix synchronization often transfers megabytes of data upon initial connection, depleting mobile battery and data plans.
Sliding Sync enables clients to request only essential data. Rather than downloading all information, clients receive the 20 most recent rooms with minimal state. As users scroll, additional ranges are requested, and the server tracks their position, sending only deltas.
When combined with edge execution, mobile clients can connect and display their room list in under 500ms, even on slower networks.
The comparison
For a homeserver catering to a small team, a comparison reveals:
Traditional (VPS)
Workers
Monthly cost (idle)
$20-50
<$1
Monthly cost (active)
$20-50
$3-10
Global latency
100-300ms
20-50ms
Time to deploy
Hours
Seconds
Maintenance
Weekly
None
DDoS protection
Additional cost
Included
Post-quantum TLS
Complex setup
Automatic
*Based on public rates and metrics published by DigitalOcean, AWS Lightsail, and Linode as of January 15, 2026.
The economic benefits become even more pronounced at scale. Traditional deployments necessitate capacity planning and over-provisioning, whereas Workers scale automatically.
The future of decentralized protocols
This project began as an experiment to determine if Matrix could operate on Workers. It demonstrated that it can, and this approach is applicable to other stateful protocols as well.
By mapping traditional stateful components to Cloudflare’s primitives—Postgres to D1, Redis to KV, and mutexes to Durable Objects—it becomes evident that complex applications do not require complex infrastructure. The operating system, database management, and network configuration were removed, leaving only the application logic and the data itself.
Workers provides the autonomy of data ownership without the overhead of infrastructure management.
The implementation has been an ongoing experiment, and contributions from others interested in this type of service are welcomed.

