Show HN: Waymark — 一个编译作业而非重放的工作流引擎
Show HN: Waymark – A workflow engine that compiles jobs instead of replaying

原始链接: https://github.com/piercefreeman/waymark

Waymark 是一个基于 Postgres 的开源库,用于持久化后台任务,优先支持 Python。它将 actions——用于 API 或数据库调用等分布式工作的普通异步函数——与 workflows——编排循环、条件、并行分支、重试、超时、持久休眠和调度等控制流——分开。工作流被一次性编译为 Rust 运行时的中间表示和字节码;状态快照到 Postgres,因此崩溃或重启的工作流可在不重新运行代码的情况下恢复,避免基于重放的确定性约束。它包含内置 Web 应用用于监控。Waymark 面向已使用 Postgres 和 Python、具有异步密集型、可重试工作负载的应用,强调本地/远程一致性与普通可测试代码。它尚不具备生产就绪状态,也不建议用于超低延迟或超高规模作业协调。通过 Python 包和 waymark-executor 安装和运行。

Waymark 是一个开源的持久执行库,定位为 Temporal 或 DBOS 的替代方案。其核心思想是编译而非重放工作流:开发者编写普通 Python 代码(计划支持 JavaScript),Waymark 遍历 AST 将逻辑映射为无栈虚拟机字节码。这实现了主动的本地错误检查并避免了解释器重放。它仅使用 Postgres 作为任务代理,支持 FastAPI 风格的动作依赖注入,并使用 Rust 核心在机器或集群间分发工作。基准测试报告约每秒 1,500 个工作流。它适用于后台任务和智能体编排,通常通过启动后台任务来替代典型的 API 请求处理。项目旨在提供 batteries-included 的体验,包含代理、Web 应用和运行时,并设有交互式网站供进一步学习。
相关文章

原文

Waymark Logo

waymark is a library to let you build durable background tasks that withstand server restarts, task crashes, and long-running jobs. It's built on Postgres, with no other infrastructure to deploy. Python is the first supported language; more are coming.

Documentation: waymark.sh

Getting started:

Running Waymark:

Python:

We ship all client and server binaries in one Python package. Install it via your package manager of choice:

Let's say you need to send welcome emails to a batch of users, but only the active ones. You want to fetch them all, filter out inactive accounts, then fan out emails in parallel. Actions are the distributed work - plain async functions, sent to your workers:

from typing import Annotated

from waymark import Depends, action

@action
async def fetch_users(
    user_ids: list[str],
    db: Annotated[Database, Depends(get_db)],
) -> list[User]:
    return await db.get_many(User, user_ids)

@action
async def send_email(
    to: str,
    subject: str,
    emailer: Annotated[EmailClient, Depends(get_email_client)],
) -> EmailResult:
    return await emailer.send(to=to, subject=subject)

The workflow is the durable control flow that orchestrates them:

import asyncio

from waymark import Workflow, workflow

@workflow
class WelcomeEmailWorkflow(Workflow):
    async def run(self, user_ids: list[str]) -> list[EmailResult]:
        users = await fetch_users(user_ids)
        active_users = [user for user in users if user.active]

        results = await asyncio.gather(
            *[
                send_email(to=user.email, subject="Welcome")
                for user in active_users
            ],
            return_exceptions=False,
        )

        return results

Run the node - the process that executes workflows and their actions - against your database:

export WAYMARK_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/waymark
export WAYMARK_HTTP_ENABLED=true  # the webapp, on http://localhost:24119
uv run waymark-executor

Then kick off the workflow from any Python process, and wait for its result:

async def welcome_users(user_ids: list[str]):
    await WelcomeEmailWorkflow().run(user_ids)

None of this executes inline in your webserver: the run is queued to Postgres and executed by the node.

Actions are the distributed work: network calls, database queries, anything that can fail and should be retried independently.

Workflows are the control flow: loops, conditionals, parallel branches. They orchestrate actions but don't do heavy lifting themselves.

Workflows are plain async Python. A few of the things they can do:

  1. Retries and timeouts, per call. By default an action runs once, like a regular function call. Wrap a call in self.run_action(...) to give it a retry policy and a timeout - see Retries & Timeouts.

    from datetime import timedelta
    
    from waymark import RetryPolicy
    
    async def run(self, order_id: str) -> Receipt:
        return await self.run_action(
            charge_card(order_id),
            retry=RetryPolicy(attempts=5, backoff_seconds=10),
            timeout=timedelta(minutes=2),
        )
  2. Branches and loops. if/elif/else, for and while compile into the workflow program and are executed by the runtime, just like your actions.

    async def run(self, order_ids: list[str]) -> list[str]:
        shipped = []
        for order_id in order_ids:
            status = await fetch_status(order_id)
            if status == "shipped":
                shipped.append(order_id)
        return shipped
  3. Parallel fan-out and durable sleep. asyncio.gather runs actions in parallel; asyncio.sleep pauses the workflow durably, surviving restarts - for a second or for a day.

    import asyncio
    
    async def run(self, user_id: str) -> str:
        profile, history = await asyncio.gather(
            fetch_profile(user_id),
            fetch_purchase_history(user_id),
            return_exceptions=False,
        )
    
        # wait a day before following up
        await asyncio.sleep(24 * 60 * 60)
        return await send_recommendations(profile, history)
  4. Schedules. Run a workflow on a cron expression or a fixed interval, with no extra infrastructure - see Scheduled Workflows.

    await schedule_workflow(DataSyncWorkflow, schedule_name="hourly", schedule="0 * * * *")
  5. A built-in webapp. waymark-executor serves a webapp showing every workflow instance, each one's timeline of calls, and the load on your nodes.

Background jobs in webapps are so frequently used that they should really be a primitive of your fullstack library: database, backend, frontend, and background jobs. Otherwise you're stuck in a situation where users either have to always make blocking requests to an API or you spin up ephemeral tasks that will be killed during re-deployments or an accidental docker crash.

After trying most of the ecosystem in the last 3 years, I believe background jobs should provide a few key features:

  • Easy to write control flow as ordinary code in the language you already use
  • Should be both very simple to test locally and very simple to deploy remotely
  • Reasonable default configurations to scale to a reasonable request volume without performance tuning

On the point of control flow, we shouldn't be forced into a DAG definition (decorators, custom syntax). It should be regular control flow just distinguished because the flows are durable and because some portions of the parallelism can be run across machines.

Nothing on the market provides this balance - waymark aims to try. We don't expect ourselves to reach best in class functionality for load performance. Instead we intend for this to scale most applications well past product market fit.

Waymark takes a different approach from replay-based workflow engines like Temporal or Vercel Workflow.

Approach How it works Constraint on users
Temporal/Vercel Workflows Replay-based. Your workflow code re-executes from the beginning on each step; completed activities return cached results. Code must be deterministic. No random(), no datetime.now(), no side effects in workflow logic.
Waymark Compile-once. Your workflow's source (any supported language, e.g. Python) → intermediate representation → bytecode for a durable virtual machine. Your code never re-runs. Code must use supported patterns. But once compiled, the runtime always knows exactly where the workflow is in its execution.

The first time a workflow is run or scheduled, it is compiled to an intermediate representation (IR); in Python, the SDK parses its run() method's AST. This IR captures your control flow - loops, conditionals, parallel branches - and is lowered to bytecode for a durable virtual machine. The Rust runtime executes the bytecode and snapshots the VM's state to Postgres as it goes, so a workflow resumes from where it was after a crash. Your original workflow definition is never re-executed during workflow recovery.

This is convenient in practice because it means that if your workflow compiles, your workflow will run as advertised. There's no need to hack around stdlib functions that are non-deterministic (like time/uuid/etc) because you'll get an error on compilation to switch these into an explicit action. The few patterns that currently slip past the compiler are listed under known issues and tracked in #772.

When should you use Waymark?

  • You're already using Postgres and a supported language (Python today), with any framework
  • You have a lot of async heavy logic that needs to be durable and can be retried if it fails (common with 3rd party API calls, db jobs, etc)
  • You want something that works the same locally as when deployed remotely
  • You want background job code to plug and play with your existing unit test & static analysis stack
  • You are focused on getting to product market fit versus scale

Performance is a top priority of waymark. That's why it's written with a Rust core and runs continuous benchmarks on CI. But it's not the only priority. After all there's only so much we can do with Postgres as an ACID backing store. Once you start to tax Postgres' capabilities you're probably at the scale where you should switch to a more complicated architecture.

When shouldn't you?

  • You have particularly latency sensitive background jobs, where you need <100ms acknowledgement and handling of each task.
  • You have a huge scale of concurrent background jobs, order of magnitude >10k actions being coordinated concurrently.
  • You have tried some existing task coordinators and need to scale your solution to the next 10x worth of traffic.

There is no shortage of robust background queues, including ones like Temporal.io/RabbitMQ that scale to millions of requests a second.

Almost all of these require a dedicated task broker that you host alongside your app. This usually isn't a huge deal during POCs but can get complex as you need to performance tune it for production. Cloud hosting of most of these are billed per-event and can get very expensive depending on how you orchestrate your jobs. They also typically force you to migrate your logic to fit the conventions of the framework.

Open source solutions like RabbitMQ have been battle tested over decades & large companies like Temporal are able to throw a lot of resources towards optimization. Both of these solutions are great choices - just intended to solve for different scopes. Expect an associated higher amount of setup and management complexity.

Important

Right now you shouldn't use waymark in any production applications. The spec is changing too quickly and we don't guarantee backwards compatibility before 1.0.0. But we would love if you try it out in your side project and see how you find it.

If you have a particular workflow that you think should be working but isn't yet compiling correctly, please file an issue.

The webapp is compiled into waymark-executor, so building from source requires Node.js (version in .node-version) and npm:

make js-deps
cargo build --bin waymark-executor

If you want to contribute, check out the contributing guidelines.

联系我们 contact @ memedata.com