跳到正文
视频中级

如何使用 Cloudflare Durable Objects

学习使用 Cloudflare Durable Objects 构建有状态应用,在边缘为无服务器应用提供一致、低延迟的协调与存储。

作者
backpine labs
发布时间
2025年2月7日
时长
12:32
在 YouTube 观看

该介绍目前仅提供英文版本。

This comprehensive tutorial introduces Cloudflare Durable Objects, a revolutionary primitive that has fundamentally changed how developers design full-stack applications. Durable Objects provide a powerful solution for building stateful applications on Cloudflare Workers, offering an alternative to complex technology stacks traditionally requiring Amazon’s API Gateway, Kafka, Redis, AWS Lambda, and Airflow.

Understanding Durable Objects

Durable Objects are challenging to define because they operate as kind of a database, kind of a cache, and also a compute solution that can execute code. A concrete Durable Object is typically implemented as a JavaScript or TypeScript class that incorporates a storage API, websocket APIs, and a scheduling API.

DOs were designed primarily to address the issue of statelessness in serverless environments. Cloudflare Workers, like typical serverless compute solutions, are designed to be stateless, meaning that all local state and variables are lost when the code execution is completed and the worker exits.

Durable Objects provide a solution for managing state in serverless applications, offering strong consistency guarantees and enabling developers to build applications that require coordination between multiple clients or persistent state across requests.

Core Capabilities & Architecture

The core capabilities of Durable Objects include three key concepts:

  1. In-Memory State: This state offers extremely low latency access but is not persistent.
  2. Storage: This is persistent until explicitly deleted. Developers can use the storage API to back up the state during write operations.
  3. Alarms: These allow developers to schedule code to be executed in the future.

Key Features

  • Stateful Edge Computing:

    • Learn how Durable Objects maintain persistent state across multiple requests
    • Understand the difference between stateless Workers and stateful Durable Objects
    • Explore how state is maintained at specific edge locations for optimal performance
  • Strong Consistency Model:

    • Discover how Durable Objects ensure data consistency across distributed environments
    • Learn about the single-threaded execution model that eliminates race conditions
    • Understand how to leverage this consistency for building reliable applications
  • WebSocket Support & Real-time Applications:

    • Implement persistent WebSocket connections for real-time communication
    • Build chat applications, live collaboration tools, and multiplayer games
    • Manage connection state and broadcast messages to multiple clients

Practical Implementation & Examples

Low-Latency State Management

Durable Objects are ideal for managing state in problems where noticeable latency severely impacts the user experience. To ensure high performance, Cloudflare attempts to instantiate the Durable Object near the user. Once an instance of the class is live, all subsequent calls can access the object’s in-memory variables with extremely low latency and no additional Input/Output (IO).

Creating Your First Durable Object

  • Set up the basic class structure and required methods
  • Understand the lifecycle of Durable Object instances
  • Learn proper initialization and cleanup patterns

State Management Techniques

  • Utilize the built-in storage API for persistent data
  • Implement in-memory state for high-performance scenarios
  • Design effective data structures for your use cases

Real-World Examples

Example 1: AI Credit System

A practical example is managing a user credit system. A user credit object class can be designed to manage the specific credit logic for one user.

  • The user’s remaining credits can be stored as a top-level variable.
  • When checking if a user has available credits, the system simply references the in-memory remaining credits value, avoiding any database lookups or additional IO.
  • The alarm API provides a solution for delayed data synchronization. For instance, after processing a request and updating the user’s credits in the DO, the system can schedule an alarm to run a task in the future (e.g., 10 minutes or 30 seconds) to sync the credit information to the billing database, thereby avoiding added latency for the user.

Example 2: Optimized User Onboarding Funnel

In an optimized onboarding process, a client required collecting several pieces of user information (business details, integration details, payment info) before a permanent account could be created and stored in the PostgreSQL database.

  • A Durable Object associated specifically with the user can be created once the user validates their email.
  • The DO temporarily stores all the necessary information collected throughout the funnel.
  • The account information is pushed to the PostgreSQL table only after all required data has been collected, ensuring data model integrity.
  • If the user abandons the process (churns), the incomplete data does not clutter the main database. Instead, an alarm can be filed to push the incomplete lead information to the sales team, detailing how far the user progressed.

This approach allows the creation of a simple TypeScript class that can be instantiated at the grain of any business problem (user, contact, account, etc.). The developer can define tailored business logic within this class and treat the object like a “hyperfocused database,” reducing the need for overly complicated data models and numerous API endpoints.

Coordination Between Objects

  • Communicate between different Durable Object instances
  • Implement distributed locking and coordination mechanisms
  • Handle cross-object transactions and data synchronization

Use Cases & Applications

The tutorial demonstrates several practical applications where Durable Objects excel:

  • Real-time Collaboration: Document editing, whiteboards, and shared workspaces
  • Gaming Applications: Multiplayer game sessions with persistent state
  • IoT Device Coordination: Managing device fleets and state synchronization
  • Rate Limiting & Quotas: Implementing distributed counters and limits
  • Session Management: User sessions with server-side state
  • Financial Applications: Transaction processing requiring strong consistency

Durable Objects at Scale

If there is skepticism regarding the scale at which Durable Objects can operate, one can look to Cloudflare, which uses DOs as a primitive to engineer and release major compute solutions for tens of thousands of developers.

Examples of large-scale products built entirely on top of Durable Objects include:

  • Cloudflare Queues: Used to build event-driven solutions, allowing services to send data to a queue for consumer workers to process.
  • Cloudflare Workflows: A platform designed to define sequences of steps to perform tasks, potentially engineered for the AI agent space.

Best Practices & Performance

Learn essential patterns for building production-ready applications:

  • Efficient State Design: Optimize data structures for your specific use cases
  • Error Handling: Implement robust error recovery and state restoration
  • Performance Optimization: Minimize cold starts and optimize memory usage
  • Scaling Considerations: Understand when and how to partition state across multiple objects

Integration with Cloudflare Ecosystem

Discover how Durable Objects integrate seamlessly with other Cloudflare services:

  • Workers Integration: Seamless communication between Workers and Durable Objects
  • KV Storage: Combining Durable Objects with Cloudflare KV for different data patterns
  • R2 Storage: Using object storage for large data alongside Durable Objects
  • Analytics & Monitoring: Tracking performance and usage patterns

Conclusion

This tutorial provides both theoretical understanding and hands-on implementation guidance, making it perfect for developers looking to build sophisticated, stateful applications on Cloudflare’s edge network. Durable Objects fundamentally change how we approach full-stack application design, offering a powerful alternative to complex traditional technology stacks while providing the consistency, performance, and scalability needed for modern applications.

继续学习