Building a serverless, post-quantum Matrix homeserver

Overview

This article demonstrates how to port a Matrix homeserver from traditional infrastructure (Synapse on VPS) to Cloudflare Workers, creating a serverless, zero-maintenance deployment with automatic post-quantum cryptography protection. The proof of concept maps PostgreSQL to D1, Redis to KV, filesystem to R2, and uses Durable Objects for atomic operations, achieving dramatic cost reduction and global low-latency performance.

What You'll Learn

1

How to map traditional stateful infrastructure components (PostgreSQL, Redis, filesystem) to Cloudflare's serverless primitives (D1, KV, R2)

2

Why different data in a Matrix homeserver requires different consistency guarantees and how to choose the right storage primitive

3

How post-quantum TLS protection works automatically on Cloudflare Workers using X25519MLKEM768 hybrid key agreement

4

How to use Durable Objects to achieve strong consistency and atomicity for operations like one-time encryption key claims

5

When to remove foreign key constraints in favor of application-level referential integrity in eventually consistent databases

Prerequisites & Requirements

  • Understanding of the Matrix protocol and homeserver architecture (event-based decentralized communication)
  • Familiarity with serverless computing concepts and Cloudflare Workers platform
  • Understanding of end-to-end encryption, TLS, and cryptographic key exchange
  • Cloudflare account with access to Workers, D1, KV, R2, and Durable Objects
  • Experience with TypeScript and deploying applications with Wrangler CLI
  • Basic understanding of OAuth 2.0/OIDC authentication flows(optional)

Key Questions Answered

Can a Matrix homeserver run on Cloudflare Workers as a serverless application?
Yes, this proof of concept demonstrates a full Matrix homeserver running on Cloudflare Workers by mapping traditional infrastructure to serverless primitives: PostgreSQL to D1 (25+ tables), Redis to KV for ephemeral state with TTL, filesystem to R2 for media storage, and Durable Objects for atomic operations like E2EE key management. The implementation supports the full Matrix E2EE stack, OAuth 2.0/OIDC, and Sliding Sync.
How does the serverless Matrix homeserver handle storage consistency without PostgreSQL?
Different data uses different Cloudflare primitives based on consistency needs. D1 (SQLite-based) handles persistent data like users, rooms, and events across 25+ tables. KV stores ephemeral data like OAuth codes with TTL expiration. Durable Objects provide single-threaded, strongly consistent storage for operations requiring atomicity, such as one-time encryption key claims where race conditions would break session establishment.
What is post-quantum cryptography and how does it protect Matrix messages on Cloudflare Workers?
Post-quantum cryptography uses lattice-based problems that remain hard even for quantum computers. Cloudflare automatically negotiates X25519MLKEM768 on all TLS 1.3 connections — a hybrid combining classical X25519 with ML-KEM (NIST-standardized). This provides two independent encryption layers: post-quantum TLS for transport protection, and Megolm E2EE for message content. Both algorithms must fail for the connection to be compromised.
How much does a serverless Matrix homeserver cost compared to a traditional VPS deployment?
For a small team, a traditional VPS deployment costs $20-50/month regardless of usage. The Workers-based deployment costs less than $1/month when idle and $3-10/month when active, since pricing is request-based. Additional savings come from included DDoS protection and automatic post-quantum TLS, which would require separate configuration and cost on traditional deployments.
Why were foreign key constraints removed from the D1 database in the Matrix homeserver?
D1's eventual consistency breaks foreign key constraints. A write to the rooms table might not be visible when a subsequent write to the events table checks the foreign key reference. The team removed all foreign keys and instead enforces referential integrity in application code, which is a necessary trade-off when working with eventually consistent databases.
What is Sliding Sync and why does it matter for mobile Matrix clients?
Traditional Matrix sync transfers megabytes of data on initial connection, draining mobile battery and data plans. Sliding Sync lets clients request only what they need — initially the 20 most recent rooms with minimal state. As users scroll, they request more ranges, and the server sends only deltas. Combined with edge execution on Workers, mobile clients can connect and render their room list in under 500ms, even on slow networks.
How do Durable Objects handle atomic one-time key claims in Matrix E2EE?
Durable Objects provide single-threaded, strongly consistent storage where no race conditions are possible. When a client claims a one-time encryption key, the UserKeysObject atomically reads the key list, removes the claimed key, and writes back the updated list in a single operation. This prevents two clients from claiming the same key, which would cause encrypted session establishment to fail.
What can the Matrix homeserver operator see when messages are end-to-end encrypted?
Any Matrix homeserver operator — whether running Synapse on a VPS or this Workers implementation — can see metadata: which rooms exist, who's in them, and when messages were sent. However, no one in the infrastructure chain can see message content because the E2EE payload is encrypted on sender devices before hitting the network. The homeserver stores only Megolm ciphertext, and private keys never leave user devices.

Key Statistics & Figures

Traditional VPS idle monthly cost
$20-50
Based on DigitalOcean, AWS Lightsail, and Linode rates as of January 2026
Workers idle monthly cost
<$1
For a small team homeserver with usage-based pricing
Workers active monthly cost
$3-10
For a small team homeserver with active usage
Traditional homeserver global latency
100-300ms
Single-region deployment (e.g., us-east-1
Workers global latency
20-50ms
Edge execution in 300+ locations worldwide
Cloudflare edge locations
300+
Workers run in 300+ locations worldwide for low-latency execution
D1 database tables
25+
Tables covering the full Matrix data model
Mobile room list render time with Sliding Sync
Under 500ms
Combined with edge execution, even on slow networks
OAuth authorization code TTL
10 minutes
OAuth codes stored in KV with 600-second expiration
Post-quantum TLS deployment date
October 2022
Cloudflare deployed post-quantum hybrid key agreement across all TLS 1.3 connections

Technologies & Tools

Some links below are affiliate links. We may earn a commission if you make a purchase.

Serverless Compute
Cloudflare Workers
Runtime for the Matrix homeserver application logic at the edge
Database
D1
SQLite-based database replacing PostgreSQL for persistent storage of users, rooms, events, and device keys
Key-value Store
Cloudflare Kv
Replaces Redis for ephemeral state like OAuth authorization codes and refresh tokens with TTL
Object Storage
R2
Replaces filesystem for Matrix media storage with content-addressed URLs and free egress
Stateful Compute
Durable Objects
Provides single-threaded, strongly consistent storage for atomic operations like E2EE key management and real-time room coordination
Protocol
Matrix
Decentralized, end-to-end encrypted communication protocol being implemented
Server
Synapse
Python-based reference Matrix homeserver that served as the starting point for the port
Language
Typescript
Language used to implement the core Matrix protocol logic on Workers
Framework
Hono
Web framework used for the Workers-based Matrix homeserver implementation
Language
Rust
Language used for Durable Object implementations (UserKeysObject)
Database
Postgresql
Traditional database used by Synapse that was replaced by D1
Cache
Redis
Traditional caching layer used by Synapse that was replaced by KV
Cryptography
X25519mlkem768
Post-quantum hybrid key agreement combining classical X25519 with ML-KEM for TLS connections
Cryptography
Megolm
Matrix's end-to-end encryption protocol for message content
Authentication
Oauth 2.0/Oidc
Modern authentication replacing legacy password flows, with PKCE authorization and RS256-signed JWT tokens
Database
Sqlite
Foundation of D1 that enabled porting queries with minimal changes
Security
TLS 1.3
Transport layer security with automatic post-quantum hybrid key agreement
CLI Tool
Wrangler
Cloudflare deployment tool — deployment is simply 'wrangler deploy'
Protocol
Sliding Sync
Matrix sync optimization that sends only requested room ranges and deltas for mobile efficiency

Key Actionable Insights

1
Map traditional infrastructure components to Cloudflare serverless primitives based on their consistency requirements rather than trying to find a single replacement. PostgreSQL maps to D1 for relational queries, Redis maps to KV for ephemeral state with TTL, filesystem maps to R2 for object storage, and mutexes map to Durable Objects for atomic operations.
This pattern applies broadly when porting any stateful application to serverless — analyze each storage component's consistency needs independently rather than seeking a one-size-fits-all solution.
2
Remove foreign key constraints when using eventually consistent databases like D1, and enforce referential integrity in application code instead. Eventual consistency means a write to one table may not be visible when a subsequent write to a related table checks the foreign key, causing spurious constraint violations.
This is a hard lesson the team learned during the port. Any application moving from strongly consistent PostgreSQL to eventually consistent storage will likely encounter this issue.
3
Use Durable Objects (or equivalent single-threaded primitives) specifically for operations that require atomicity, such as one-time encryption key claims. Keep the scope narrow — only route operations through Durable Objects when eventual consistency would cause correctness issues, and let everything else flow through D1.
The implementation uses Durable Objects for only three specific use cases: E2EE key management (UserKeysObject), real-time room events (RoomObject), and to-device message queues (UserSyncObject). Being selective avoids unnecessary coordination overhead.
4
Leverage platform-provided post-quantum TLS rather than implementing it yourself. On Cloudflare Workers, X25519MLKEM768 is automatically negotiated on all TLS 1.3 connections, eliminating the need to upgrade OpenSSL/BoringSSL, configure cipher suites, test client compatibility, and monitor TLS negotiation failures.
Chrome, Firefox, and Edge all support X25519MLKEM768, and mobile apps using platform TLS stacks inherit this support. The security posture improves automatically as Cloudflare's PQC deployment expands.
5
Implement Sliding Sync for mobile Matrix clients to dramatically reduce initial sync payload size. Instead of transferring megabytes of room data on connection, serve only the 20 most recent rooms with minimal state and send deltas as users scroll through their room list.
Combined with edge execution, this approach enables mobile clients to connect and render their room list in under 500ms even on slow networks, compared to the traditional full sync approach that drains battery and data plans.
6
Design two independent encryption layers for communication systems: a transport layer (TLS) that protects data in transit and can be upgraded to post-quantum, and an application layer (E2EE) that protects message content end-to-end. This ensures the server operator never sees plaintext regardless of infrastructure trust level.
In this architecture, the Worker terminates TLS but receives only Megolm ciphertext. Even if TLS were compromised, message content remains protected by E2EE. The layers operate independently so upgrading one doesn't affect the other.

Common Pitfalls

1
Using foreign key constraints in D1 (or other eventually consistent databases) will cause spurious failures. A write to a parent table may not be visible when a subsequent write to a child table checks the foreign key reference, leading to constraint violations even when data integrity is actually maintained.
The team learned this the hard way during the port. The solution is to remove all foreign keys and enforce referential integrity in application code instead.
2
Treating all data with the same consistency requirements when migrating to serverless primitives. Not all operations need strong consistency, and routing everything through Durable Objects would be unnecessarily slow, while storing everything in KV would lose the relational query capabilities needed for the Matrix data model.
The key insight is to analyze each data type's consistency needs independently: D1 for queryable persistent data, KV for ephemeral state, Durable Objects only for operations requiring atomicity.
3
Using traditional full Matrix sync for mobile clients, which transfers megabytes of data on initial connection. This drains mobile battery and data plans unnecessarily, especially when users only need to see their most recent conversations.
Implementing Sliding Sync solves this by letting clients request exactly what they need — starting with the 20 most recent rooms and loading more on demand via deltas.
4
Attempting to manually configure post-quantum TLS on a traditional Matrix deployment requires upgrading OpenSSL or BoringSSL, configuring cipher suite preferences, testing client compatibility across all Matrix apps, monitoring for TLS negotiation failures, and staying current as PQC standards evolve.
Using a platform like Cloudflare Workers that provides post-quantum TLS automatically eliminates this entire operational burden. Chrome, Firefox, and Edge already support X25519MLKEM768.

Related Concepts

Matrix Protocol And Federation
Serverless Architecture Patterns
Post-quantum Cryptography (ml-kem, X25519)
End-to-end Encryption (megolm, Olm)
Edge Computing And Global Distribution
Eventually Consistent Databases
Durable Objects And Strong Consistency
Oauth 2.0/Oidc Authentication
Sliding Sync Protocol
Decentralized Communication Protocols
Conflict Resolution In Distributed Systems
State Machine Replication
Hybrid Cryptographic Key Exchange
Content-addressed Storage
Zero-trust Infrastructure