Close Menu
    Latest Post

    Suspected Russian Actor Linked to CANFAIL Malware Attacks on Ukrainian Organizations

    February 22, 2026

    Trump Reinstates De Minimis Exemption Suspension Despite Supreme Court Ruling

    February 22, 2026

    How Cloudflare Mitigated a Vulnerability in its ACME Validation Logic

    February 21, 2026
    Facebook X (Twitter) Instagram
    Trending
    • Suspected Russian Actor Linked to CANFAIL Malware Attacks on Ukrainian Organizations
    • Trump Reinstates De Minimis Exemption Suspension Despite Supreme Court Ruling
    • How Cloudflare Mitigated a Vulnerability in its ACME Validation Logic
    • Demis Hassabis and John Jumper Receive Nobel Prize in Chemistry
    • How to Cancel Your Google Pixel Watch Fitbit Premium Trial
    • GHD Speed Hair Dryer Review: Powerful Performance and User-Friendly Design
    • An FBI ‘Asset’ Helped Run a Dark Web Site That Sold Fentanyl-Laced Drugs for Years
    • The Next Next Job, a framework for making big career decisions
    Facebook X (Twitter) Instagram Pinterest Vimeo
    NodeTodayNodeToday
    • Home
    • AI
    • Dev
    • Guides
    • Products
    • Security
    • Startups
    • Tech
    • Tools
    NodeTodayNodeToday
    Home»Tools»Building a Serverless, Post-Quantum Matrix Homeserver
    Tools

    Building a Serverless, Post-Quantum Matrix Homeserver

    Samuel AlejandroBy Samuel AlejandroFebruary 13, 2026No Comments9 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    src 13d1efo featured
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    Deploy to Cloudflare

    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.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleI’m Doing a Little Consulting
    Next Article Russia Blocks WhatsApp, Citing Non-Compliance with Local Laws, Promotes State-Owned Max App
    Samuel Alejandro

    Related Posts

    Tools

    How Cloudflare Mitigated a Vulnerability in its ACME Validation Logic

    February 21, 2026
    Tools

    Mozilla Leaders Advocate for Open Source AI as a Path to Sovereignty at India AI Impact Summit

    February 21, 2026
    Dev

    Docker vs Kubernetes in Production: A Security-First Decision Framework

    February 21, 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Latest Post

    ChatGPT Mobile App Surpasses $3 Billion in Consumer Spending

    December 21, 202513 Views

    Creator Tayla Cannon Lands $1.1M Investment for Rebuildr PT Software

    December 21, 202511 Views

    Automate Your iPhone’s Always-On Display for Better Battery Life and Privacy

    December 21, 202510 Views
    Stay In Touch
    • Facebook
    • YouTube
    • TikTok
    • WhatsApp
    • Twitter
    • Instagram
    About

    Welcome to NodeToday, your trusted source for the latest updates in Technology, Artificial Intelligence, and Innovation. We are dedicated to delivering accurate, timely, and insightful content that helps readers stay ahead in a fast-evolving digital world.

    At NodeToday, we cover everything from AI breakthroughs and emerging technologies to product launches, software tools, developer news, and practical guides. Our goal is to simplify complex topics and present them in a clear, engaging, and easy-to-understand way for tech enthusiasts, professionals, and beginners alike.

    Latest Post

    Suspected Russian Actor Linked to CANFAIL Malware Attacks on Ukrainian Organizations

    February 22, 20260 Views

    Trump Reinstates De Minimis Exemption Suspension Despite Supreme Court Ruling

    February 22, 20260 Views

    How Cloudflare Mitigated a Vulnerability in its ACME Validation Logic

    February 21, 20260 Views
    Recent Posts
    • Suspected Russian Actor Linked to CANFAIL Malware Attacks on Ukrainian Organizations
    • Trump Reinstates De Minimis Exemption Suspension Despite Supreme Court Ruling
    • How Cloudflare Mitigated a Vulnerability in its ACME Validation Logic
    • Demis Hassabis and John Jumper Receive Nobel Prize in Chemistry
    • How to Cancel Your Google Pixel Watch Fitbit Premium Trial
    Facebook X (Twitter) Instagram Pinterest
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    • Disclaimer
    • Cookie Policy
    © 2026 NodeToday.

    Type above and press Enter to search. Press Esc to cancel.