关于 inngest-durable-functions
面向 TypeScript 的技能,介绍如何用 Inngest Durable Functions 构建可容错的长时运行工作流,涵盖持久化步骤、触发器、重试、幂等性与取消。
主要功能
- 01将操作组织为持久化步骤
- 02配置事件和定时触发器
- 03设置重试与幂等性
- 04处理取消和错误
- 05应用执行限制与检查点
适用场景
- 01构建故障后可恢复的工作流
- 02独立重试外部调用
- 03防止事件重复处理
- 04按事件或超时取消工作流
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ inngest/ inngest-skills --skill inngest-durable-functions安装后在 Claude Code 中输入/inngest-durable-functions确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/checkpointing.mderror-handling.mdobservability.mdstep-execution.md详细介绍
Inngest 持久化函数
掌握 Inngest 的持久化执行模型,构建容错的长时间运行工作流。本技能涵盖从触发器到错误处理的完整生命周期。
这些技能专注于 TypeScript。 如需 Python 或 Go 相关内容,请参阅 Inngest 文档以获取特定语言的指导。核心概念适用于所有语言。
需要了解的核心概念
持久化执行模型
- 每个步骤都应封装副作用和非确定性代码
- 记忆化可防止重新执行已完成的步骤
- 状态持久化可在基础设施故障后保留状态
- 自动重试,并可配置重试次数
步骤执行流程
// ❌ BAD: Non-deterministic logic outside steps
async ({ event, step }) => {
const timestamp = Date.now(); // This runs multiple times!
const result = await step.run("process-data", () => {
return processData(event.data);
});
};
// ✅ GOOD: All non-deterministic logic in steps
async ({ event, step }) => {
const result = await step.run("process-with-timestamp", () => {
const timestamp = Date.now(); // Only runs once
return processData(event.data, timestamp);
});
};
函数限制
每个 Inngest 函数都有以下硬性限制:
- 每次函数运行最多 1,000 个步骤
- 每个步骤返回的数据最多 4MB
- 函数运行状态总量最多 32MB,包括事件数据、步骤输出和函数输出
- 每个步骤都会产生单独的 HTTP 请求(约 50-100ms 开销)
如果达到这些限制,请将函数拆分成更小的函数,并通过 step.invoke() 或 step.sendEvent() 连接。
何时使用步骤
始终使用 step.run() 封装:
- API 调用和网络请求
- 数据库读写
- 文件 I/O 操作
- 任何非确定性操作
- 任何希望在失败时独立重试的操作
绝不要使用 step.run() 封装:
- 纯计算和数据转换
- 简单的验证逻辑
- 没有副作用的确定性操作
- 日志记录(请在步骤外使用)
创建函数
基本函数结构
const processOrder = inngest.createFunction(
{
id: "process-order", // Unique, never change this
triggers: [{ event: "order/created" }],
retries: 4, // Default: 4 retries per step
concurrency: 10 // Max concurrent executions
},
async ({ event, step }) => {
// Your durable workflow
}
);
步骤 ID 和记忆化
// Step IDs can be reused - Inngest handles counters automatically
const data = await step.run("fetch-data", () => fetchUserData());
const more = await step.run("fetch-data", () => fetchOrderData()); // Different execution
// Use descriptive IDs for clarity
await step.run("validate-payment", () => validatePayment(event.data.paymentId));
await step.run("charge-customer", () => chargeCustomer(event.data));
await step.run("send-confirmation", () => sendEmail(event.data.email));
触发器和事件
事件触发器
在 createFunction 第一个参数中的 triggers 数组里定义触发器:
// Single event trigger
inngest.createFunction(
{ id: "my-fn", triggers: [{ event: "user/signup" }] },
async ({ event }) => { /* ... */ }
);
// Event with conditional filter
inngest.createFunction(
{ id: "my-fn", triggers: [{ event: "user/action", if: 'event.data.action == "purchase" && event.data.amount > 100' }] },
async ({ event }) => { /* ... */ }
);
// Multiple triggers (up to 10)
inngest.createFunction(
{
id: "my-fn",
triggers: [
{ event: "user/signup" },
{ event: "user/login", if: 'event.data.firstLogin == true' },
{ cron: "0 9 * * *" } // Daily at 9 AM
]
},
async ({ event }) => { /* ... */ }
);
Cron 触发器
// Basic cron
inngest.createFunction(
{ id: "my-fn", triggers: [{ cron: "0 */6 * * *" }] }, // Every 6 hours
async ({ step }) => { /* ... */ }
);
// With timezone
inngest.createFunction(
{ id: "my-fn", triggers: [{ cron: "TZ=Europe/Paris 0 12 * * 5" }] }, // Fridays at noon Paris time
async ({ step }) => { /* ... */ }
);
// Combine with events
inngest.createFunction(
{
id: "my-fn",
triggers: [
{ event: "manual/report.requested" },
{ cron: "0 0 * * 0" } // Weekly on Sunday
]
},
async ({ event, step }) => { /* ... */ }
);
函数调用
// Invoke another function as a step
const result = await step.invoke("generate-report", {
function: generateReportFunction,
data: { userId: event.data.userId }
});
// Use returned data
await step.run("process-report", () => {
return processReport(result);
});
幂等性策略
事件级幂等性(生产者端)
// Prevent duplicate events with custom ID
await inngest.send({
id: `checkout-completed-${cartId}`, // 24-hour deduplication
name: "cart/checkout.completed",
data: { cartId, email: "[email protected]" }
});
函数级幂等性(消费者端)
const sendEmail = inngest.createFunction(
{
id: "send-checkout-email",
triggers: [{ event: "cart/checkout.completed" }],
// Only run once per cartId per 24 hours
idempotency: "event.data.cartId"
},
async ({ event, step }) => {
// This function won't run twice for same cartId
}
);
// Complex idempotency keys
const processUserAction = inngest.createFunction(
{
id: "process-user-action",
triggers: [{ event: "user/action.performed" }],
// Unique per user + organization combination
idempotency: 'event.data.userId + "-" + event.data.organizationId'
},
async ({ event, step }) => {
/* ... */
}
);
取消模式
基于事件的取消
在表达式中,event = 原始触发事件,async = 正在匹配的新事件。完整详情请参阅表达式语法参考。
const processOrder = inngest.createFunction(
{
id: "process-order",
triggers: [{ event: "order/created" }],
cancelOn: [
{
event: "order/cancelled",
if: "event.data.orderId == async.data.orderId"
}
]
},
async ({ event, step }) => {
await step.sleepUntil("wait-for-payment", event.data.paymentDue);
// Will be cancelled if order/cancelled event received
await step.run("charge-payment", () => processPayment(event.data));
}
);
超时取消
const processWithTimeout = inngest.createFunction(
{
id: "process-with-timeout",
triggers: [{ event: "long/process.requested" }],
timeouts: {
start: "5m", // Cancel if not started within 5 minutes
finish: "30m" // Cancel if not finished within 30 minutes
}
},
async ({ event, step }) => {
/* ... */
}
);
处理取消清理
// Listen for cancellation events
const cleanupCancelled = inngest.createFunction(
{ id: "cleanup-cancelled-process", triggers: [{ event: "inngest/function.cancelled" }] },
async ({ event, step }) => {
if (event.data.function_id === "process-order") {
await step.run("cleanup-resources", () => {
return cleanupOrderResources(event.data.run_id);
});
}
}
);
错误处理和重试
默认重试行为
- 每个步骤总共 5 次尝试(1 次初始尝试 + 4 次重试)
- 带抖动的指数退避
- 每个步骤的重试计数器相互独立
自定义重试配置
const reliableFunction = inngest.createFunction(
{
id: "reliable-function",
triggers: [{ event: "critical/task" }],
retries: 10 // Up to 10 retries per step
},
async ({ event, step, attempt }) => {
// `attempt` is the function-level attempt counter (0-indexed)
// It tracks retries for the currently executing step, not the overall function
if (attempt > 5) {
// Different logic for later attempts of the current step
}
}
);
不可重试的错误
对于重试后也不会成功的代码,阻止其重试。
import { NonRetriableError } from "inngest";
const processUser = inngest.createFunction(
{ id: "process-user", triggers: [{ event: "user/process.requested" }] },
async ({ event, step }) => {
const user = await step.run("fetch-user", async () => {
const user = await db.users.findOne(event.data.userId);
if (!user) {
// Don't retry - user doesn't exist
throw new NonRetriableError("User not found, stopping execution");
}
return user;
});
// Continue processing...
}
);
自定义重试时机
import { RetryAfterError } from "inngest";
const respectRateLimit = inngest.createFunction(
{ id: "api-call", triggers: [{ event: "api/call.requested" }] },
async ({ event, step }) => {
await step.run("call-api", async () => {
const response = await externalAPI.call(event.data);
if (response.status === 429) {
// Retry after specific time from API
const retryAfter = response.headers["retry-after"];
throw new RetryAfterError("Rate limited", `${retryAfter}s`);
}
return response.data;
});
}
);
日志记录最佳实践
正确配置日志记录
import winston from "winston";
// Configure logger
const logger = winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [new winston.transports.Console()]
});
const inngest = new Inngest({
id: "my-app",
logger // Pass logger to client
});
// Or use the built-in ConsoleLogger for simple log level control
import { ConsoleLogger, Inngest } from "inngest";
const inngest = new Inngest({
id: "my-app",
logger: new ConsoleLogger({ level: "debug" }) // "debug" | "info" | "warn" | "error"
});
⚠️ v4 破坏性变更: logLevel 选项已移除。请改用 logger 选项,并使用 ConsoleLogger 或自定义日志记录器。
函数日志记录模式
const processData = inngest.createFunction(
{ id: "process-data", triggers: [{ event: "data/process.requested" }] },
async ({ event, step, logger }) => {
// ✅ GOOD: Log inside steps to avoid duplicates
const result = await step.run("fetch-data", async () => {
logger.info("Fetching data for user", { userId: event.data.userId });
return await fetchUserData(event.data.userId);
});
// ❌ AVOID: Logging outside steps can duplicate
// logger.info("Processing complete"); // This could run multiple times!
await step.run("log-completion", async () => {
logger.info("Processing complete", { resultCount: result.length });
});
}
);
性能优化
检查点
v4 中默认启用检查点。它允许函数在执行期间定期持久化状态,减少步骤之间的延迟。
// Checkpointing is enabled by default in v4
// Configure maxRuntime for serverless platforms (set to 60-80% of platform timeout)
const realTimeFunction = inngest.createFunction(
{
id: "real-time-function",
triggers: [{ event: "realtime/process" }],
checkpointing: {
maxRuntime: "50s", // For serverless with 60s timeout
}
},
async ({ event, step }) => {
// Steps execute immediately with periodic checkpointing
const result1 = await step.run("step-1", () => process1(event.data));
const result2 = await step.run("step-2", () => process2(result1));
return { result2 };
}
);
// Disable checkpointing if needed
const legacyFunction = inngest.createFunction(
{
id: "legacy-function",
triggers: [{ event: "legacy/process" }],
checkpointing: false
},
async ({ event, step }) => { /* ... */ }
);
高级模式
条件步骤执行
const conditionalProcess = inngest.createFunction(
{ id: "conditional-process", triggers: [{ event: "process/conditional" }] },
async ({ event, step }) => {
const userData = await step.run("fetch-user", () => {
return getUserData(event.data.userId);
});
// Conditional step execution
if (userData.isPremium) {
await step.run("premium-processing", () => {
return processPremiumFeatures(userData);
});
}
// Always runs
await step.run("standard-processing", () => {
return processStandardFeatures(userData);
});
}
);
错误恢复模式
const robustProcess = inngest.createFunction(
{ id: "robust-process", triggers: [{ event: "process/robust" }] },
async ({ event, step }) => {
let primaryResult;
try {
primaryResult = await step.run("primary-service", () => {
return callPrimaryService(event.data);
});
} catch (error) {
// Fallback to secondary service
primaryResult = await step.run("fallback-service", () => {
return callSecondaryService(event.data);
});
}
return { result: primaryResult };
}
);
应避免的常见错误
- ❌ 在步骤外执行非确定性代码
- ❌ 在步骤外调用数据库
- ❌ 在步骤外记录日志(会导致重复)
- ❌ 部署后更改步骤 ID
- ❌ 未处理 NonRetriableError 情况
- ❌ 忽略关键函数的幂等性
后续步骤
- 查看 inngest-steps,了解详细的步骤方法参考
- 查看 references/step-execution.md,了解详细的步骤模式
- 查看 references/error-handling.md,了解全面的错误处理策略
- 查看 references/observability.md,了解监控和追踪设置
- 查看 references/checkpointing.md,了解性能优化详情
本技能涵盖 Inngest 的持久化函数模式。有关事件发送和 Webhook 处理,请参阅 inngest-events 技能。
评论
支持 Markdown