Back

What is Durable Object?

I recently came across a YouTube video about Aaron Francis talking about Durable Objects with Cloudflare's Josh Howard (https://www.youtube.com/watch?v=C5-741uQPVU), and it was extremely interesting to me. I've always been fascinated by the concept of a "one tenant, one database" structure, and in that video, it seems like Durable Objects are a perfect solution for this pattern.

My understanding of Durable Objects is that they are essentially Cloudflare Workers with enhanced capabilities: they maintain state and have access to storage systems like KV and D1. This makes them perfect for building APIs and real-time apps that need WebSocket-like functionalities.


The Key Difference from Regular Workers

Unlike traditional Cloudflare Workers, which are stateless, Durable Objects provide:

In memory States

Each Durable Object instance maintains its own in-memory state that persists across requests until the end of the lifecycle of the object. This is useful for storing data that needs to be accessed by multiple requests, such as:

  • user sessions
  • game state
  • chat state

Strong consistency

All requests to a specific Durable Object are routed to the same instance, ensuring consistent state

Storage access

Direct integration with Cloudflare's storage services (KV, D1, R2)

Low latency

The object is created near to the first request of the user


Perfect for Multi-Tenancy

The "one tenant, one database" pattern becomes incredibly elegant with Durable Objects, and making scalable SaaS applications easier. Instead of managing complex database sharding or partitioning logic, you can:

  1. Create one Durable Object instance per tenant
  2. Store tenant-specific data directly in the object's state
  3. Access storage systems (KV, D1) scoped to that tenant
  4. Handle real-time connections (WebSockets) for that specific tenant
Durable Object Structure

Use Cases

Durable Objects excel in scenarios that require:

Real-time applications

Chat rooms, collaborative editing, live updates. Imagine you have one web socket server per each tenant, and you do not need to consider the scalability of the web socket server.

Multi-tenant SaaS

Isolating data and logic per tenant. For example, you can have one Durable Object instance per tenant, and each instance will have its own state and storage. Scalability is also easier to manage.


Example Project

To demonstrate Durable Objects in practice, I built a collaborative note-taking application that showcases the multi-tenancy pattern.

Demo

Tech Stack:

Links:

Architecture Overview

Each organization gets its own Durable Object instance, which manages:

  • D1 Database: Stores Item records, where each item represents a simple record with a title
  • KV Storage: Persists the content of the collaborative note editor

The Cloudflare Worker serves three main purposes:

  1. Serve the React application
  2. Handle API requests
  3. Serve y-server for real-time collaboration