restate
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRestate Durable Execution Framework
Restate 持久执行框架
Restate is a durable execution framework that makes applications resilient to failures. Use this skill when building:
- Durable workflows with automatic retries
- Services with persisted state (Virtual Objects)
- Microservice orchestration with transactional guarantees
- Event processing with exactly-once semantics
- Long-running tasks that survive crashes
Restate是一个持久执行框架,可让应用具备故障恢复能力。在构建以下内容时使用本Skill:
- 具备自动重试机制的持久工作流
- 带有持久化状态的服务(Virtual Objects)
- 具备事务保证的微服务编排
- 具备精确一次语义的事件处理
- 可在崩溃后继续运行的长时间任务
When to Use Restate
何时使用Restate
Use Restate when:
- Building workflows that must complete despite failures
- Need automatic retry and recovery without manual retry logic
- Building stateful services (shopping carts, user sessions, payment processing)
- Orchestrating multiple services with saga/compensation patterns
- Processing events with exactly-once delivery guarantees
- Scheduling durable timers and cron jobs
在以下场景使用Restate:
- 构建必须在故障情况下仍能完成的工作流
- 无需手动编写重试逻辑,即可实现自动重试与恢复
- 构建有状态服务(购物车、用户会话、支付处理)
- 使用Saga/补偿模式编排多个服务
- 处理具备精确一次投递保证的事件
- 调度持久化定时器和定时任务
Core Concepts
核心概念
Service Types
服务类型
Restate supports three service types:
-
Services - Stateless handlers with durable execution
- Use for: microservice orchestration, sagas, idempotent requests
-
Virtual Objects - Stateful handlers with K/V state isolated per key
- Use for: entities (shopping cart), state machines, actors, stateful event processing
- Only one handler runs at a time per object key (consistency guarantee)
-
Workflows - Special Virtual Objects wherehandler executes exactly once
run- Use for: order processing, human-in-the-loop, long-running provisioning
See Services Concepts for detailed comparison.
Restate支持三种服务类型:
-
Services - 具备持久执行能力的无状态处理器
- 适用场景:微服务编排、Saga模式、幂等请求
-
Virtual Objects - 为每个键隔离KV状态的有状态处理器
- 适用场景:实体(购物车)、状态机、Actor、有状态事件处理
- 每个对象键同一时间仅运行一个处理器(一致性保证)
-
Workflows - 特殊的Virtual Objects,其中处理器仅执行一次
run- 适用场景:订单处理、人工介入流程、长时间资源调配
更多详细对比请查看服务概念。
Durable Building Blocks
持久化构建块
Restate provides these building blocks through the SDK context:
- Journaled actions () - Persist results of side effects
ctx.run() - State () - K/V state for Virtual Objects
ctx.get/set/clear - Timers () - Durable sleep that survives restarts
ctx.sleep() - Service calls () - RPC with automatic retries
ctx.serviceClient() - Awakeables - Wait for external events/signals
See Durable Building Blocks.
Restate通过SDK上下文提供以下构建块:
- 日志化操作 () - 持久化副作用的执行结果
ctx.run() - 状态管理 () - 为Virtual Objects提供KV状态
ctx.get/set/clear - 定时器 () - 可在重启后继续生效的持久化休眠
ctx.sleep() - 服务调用 () - 具备自动重试机制的RPC
ctx.serviceClient() - Awakeables - 等待外部事件/信号
更多内容请查看持久化构建块。
TypeScript SDK Quick Reference
TypeScript SDK 快速参考
Installation
安装
bash
npm install @restatedev/restate-sdkbash
npm install @restatedev/restate-sdkBasic Service
基础服务
typescript
import * as restate from "@restatedev/restate-sdk";
const myService = restate.service({
name: "MyService",
handlers: {
greet: async (ctx: restate.Context, name: string) => {
return "Hello, " + name + "!";
},
},
});
restate.endpoint().bind(myService).listen(9080);typescript
import * as restate from "@restatedev/restate-sdk";
const myService = restate.service({
name: "MyService",
handlers: {
greet: async (ctx: restate.Context, name: string) => {
return "Hello, " + name + "!";
},
},
});
restate.endpoint().bind(myService).listen(9080);Virtual Object (Stateful)
虚拟对象(有状态)
typescript
const counter = restate.object({
name: "Counter",
handlers: {
add: async (ctx: restate.ObjectContext, value: number) => {
const current = (await ctx.get<number>("count")) ?? 0;
ctx.set("count", current + value);
return current + value;
},
get: restate.handlers.object.shared(
async (ctx: restate.ObjectSharedContext) => {
return (await ctx.get<number>("count")) ?? 0;
}
),
},
});typescript
const counter = restate.object({
name: "Counter",
handlers: {
add: async (ctx: restate.ObjectContext, value: number) => {
const current = (await ctx.get<number>("count")) ?? 0;
ctx.set("count", current + value);
return current + value;
},
get: restate.handlers.object.shared(
async (ctx: restate.ObjectSharedContext) => {
return (await ctx.get<number>("count")) ?? 0;
}
),
},
});Workflow
工作流
typescript
const paymentWorkflow = restate.workflow({
name: "PaymentWorkflow",
handlers: {
run: async (ctx: restate.WorkflowContext, payment: Payment) => {
// Step 1: Reserve funds
const reservation = await ctx.run("reserve", () =>
reserveFunds(payment)
);
// Step 2: Wait for approval (awakeable)
const approved = await ctx.promise<boolean>("approval");
if (!approved) {
await ctx.run("cancel", () => cancelReservation(reservation));
return { status: "cancelled" };
}
// Step 3: Complete payment
await ctx.run("complete", () => completePayment(reservation));
return { status: "completed" };
},
approve: async (ctx: restate.WorkflowSharedContext) => {
ctx.promise<boolean>("approval").resolve(true);
},
reject: async (ctx: restate.WorkflowSharedContext) => {
ctx.promise<boolean>("approval").resolve(false);
},
},
});typescript
const paymentWorkflow = restate.workflow({
name: "PaymentWorkflow",
handlers: {
run: async (ctx: restate.WorkflowContext, payment: Payment) => {
// Step 1: Reserve funds
const reservation = await ctx.run("reserve", () =>
reserveFunds(payment)
);
// Step 2: Wait for approval (awakeable)
const approved = await ctx.promise<boolean>("approval");
if (!approved) {
await ctx.run("cancel", () => cancelReservation(reservation));
return { status: "cancelled" };
}
// Step 3: Complete payment
await ctx.run("complete", () => completePayment(reservation));
return { status: "completed" };
},
approve: async (ctx: restate.WorkflowSharedContext) => {
ctx.promise<boolean>("approval").resolve(true);
},
reject: async (ctx: restate.WorkflowSharedContext) => {
ctx.promise<boolean>("approval").resolve(false);
},
},
});Key SDK Patterns
关键SDK模式
typescript
// Journaled action - result persisted, replayed on retry
const result = await ctx.run("action-name", async () => {
return await callExternalApi();
});
// Durable timer - survives restarts
await ctx.sleep(60_000); // 60 seconds
// Call another service
const client = ctx.serviceClient(OtherService);
const response = await client.handler(input);
// Async call (fire and forget)
ctx.serviceSendClient(OtherService).handler(input);
// Delayed call
ctx.serviceSendClient(OtherService, { delay: 60_000 }).handler(input);
// Awakeable - wait for external signal
const { id, promise } = ctx.awakeable<string>();
// Give `id` to external system, then:
const result = await promise;
// Random (deterministic)
const value = ctx.rand.random();
const uuid = ctx.rand.uuidv4();typescript
// Journaled action - result persisted, replayed on retry
const result = await ctx.run("action-name", async () => {
return await callExternalApi();
});
// Durable timer - survives restarts
await ctx.sleep(60_000); // 60 seconds
// Call another service
const client = ctx.serviceClient(OtherService);
const response = await client.handler(input);
// Async call (fire and forget)
ctx.serviceSendClient(OtherService).handler(input);
// Delayed call
ctx.serviceSendClient(OtherService, { delay: 60_000 }).handler(input);
// Awakeable - wait for external signal
const { id, promise } = ctx.awakeable<string>();
// Give `id` to external system, then:
const result = await promise;
// Random (deterministic)
const value = ctx.rand.random();
const uuid = ctx.rand.uuidv4();Running Locally
本地运行
- Start Restate server:
bash
npx @restatedev/restate-server- Run your service:
bash
npx ts-node src/app.ts- Register service with Restate:
bash
npx @restatedev/restate deployments register http://localhost:9080- Invoke handlers via HTTP:
bash
undefined- 启动Restate服务器:
bash
npx @restatedev/restate-server- 运行你的服务:
bash
npx ts-node src/app.ts- 向Restate注册服务:
bash
npx @restatedev/restate deployments register http://localhost:9080- 通过HTTP调用处理器:
bash
undefinedService handler
Service handler
curl localhost:8080/MyService/greet -H 'content-type: application/json' -d '"World"'
curl localhost:8080/MyService/greet -H 'content-type: application/json' -d '"World"'
Virtual Object handler (with key)
Virtual Object handler (with key)
curl localhost:8080/Counter/user123/add -H 'content-type: application/json' -d '5'
curl localhost:8080/Counter/user123/add -H 'content-type: application/json' -d '5'
Start workflow
Start workflow
curl localhost:8080/PaymentWorkflow/order-456/run -H 'content-type: application/json' -d '{"amount": 100}'
undefinedcurl localhost:8080/PaymentWorkflow/order-456/run -H 'content-type: application/json' -d '{"amount": 100}'
undefinedDocumentation References
文档参考
Concepts
概念
- Services - Service types and use cases
- Invocations - How invocations work
- Durable Execution - Execution guarantees
- Durable Building Blocks - SDK primitives
- Services - 服务类型与适用场景
- Invocations - 调用机制说明
- Durable Execution - 执行保证
- Durable Building Blocks - SDK原语
TypeScript SDK
TypeScript SDK
- Overview - SDK setup and service definitions
- State - K/V state management
- Journaling Results - Side effects and
ctx.run() - Durable Timers - Sleep and scheduling
- Service Communication - Calling other services
- Awakeables - External events
- Workflows - Workflow implementation
- Error Handling - Error patterns
- Serving - Running services
- Testing - Testing strategies
- Clients - Client SDK
- 概述 - SDK设置与服务定义
- 状态管理 - KV状态管理
- 结果日志化 - 副作用与
ctx.run() - 持久化定时器 - 休眠与调度
- 服务通信 - 调用其他服务
- Awakeables - 外部事件处理
- 工作流 - 工作流实现
- 错误处理 - 错误模式
- 服务部署 - 运行服务
- 测试 - 测试策略
- 客户端 - 客户端SDK
Guides
指南
- Error Handling - Comprehensive error handling
- Sagas - Saga pattern with compensations
- Cron Jobs - Scheduled tasks
- Parallelizing Work - Fan-out patterns
- Databases - Database integration
- Lambda Deployment - AWS Lambda deployment
- 错误处理 - 全面的错误处理方案
- Sagas模式 - 带补偿的Saga模式
- 定时任务 - 调度任务
- 并行处理 - 扇出模式
- 数据库集成 - 数据库集成
- Lambda部署 - AWS Lambda部署
Use Cases
适用场景
- Workflows
- Async Tasks
- Event Processing
- Microservice Orchestration
- 工作流
- 异步任务
- 事件处理
- 微服务编排
Operations
运维
- HTTP Invocation
- Service Registration
- Versioning
- Architecture
- HTTP调用
- 服务注册
- 版本管理
- 架构
Important Guidelines
重要指南
-
Side effects must be wrapped in- External calls, random values, timestamps must go through the context to be journaled and replayed correctly.
ctx.run() -
State access only in Virtual Objects/Workflows - Plain Services don't have state access.
-
Handlers must be deterministic - Same inputs should produce same outputs. Usefor randomness.
ctx.rand -
One handler per Virtual Object key at a time - Restate ensures consistency by queuing concurrent requests to the same key.
-
Workflowshandler executes exactly once - Use other handlers to query/signal the workflow.
run -
Register services after code changes - Runto update handler definitions.
restate deployments register
Generated from Restate documentation. Run to update.
scripts/sync-docs.sh- 副作用必须包裹在中 - 外部调用、随机值、时间戳必须通过上下文执行,以确保正确记录日志并可重放。
ctx.run() - 仅在Virtual Objects/Workflows中访问状态 - 普通Services无法访问状态。
- 处理器必须具备确定性 - 相同输入应产生相同输出。使用生成随机值。
ctx.rand - 同一Virtual Object键同一时间仅运行一个处理器 - Restate通过对同一键的并发请求进行排队来保证一致性。
- Workflows的处理器仅执行一次 - 使用其他处理器查询或向工作流发送信号。
run - 代码变更后重新注册服务 - 运行以更新处理器定义。
restate deployments register
内容基于Restate文档生成。运行可更新内容。
scripts/sync-docs.shLicense
许可证
The content in the directory is derived from the Restate documentation and TypeScript SDK.
references/