DRubyRustUG

Wrocław, DRUG

Background jobs,
organized

Temporal, CEL, and the log that never calls itself event sourcing

Robert Pankowecki

Tweet by Andrzej Krzywda: 40% of devs try to reinvent RubyLLM, 40% try to reinvent AmpCode. That's my conclusion after talking to many devs at the recent conferences and meetups.

It always starts with one job


job run_agent_task(task):
  workspace = clone_repo(task.repo)           # 3 minutes
  image     = build_image(workspace)          # 30 minutes
  result    = run_agent(image, task.prompt)   # 2 hours
  run_tests(result)                           # 20 minutes
  open_pull_request(result)                   # 2 seconds, flaky

The last call returns a 502. Retry the job: 3 hours, gone.

Too long for a request. Too flaky to run once. Too expensive to run twice.

From a Rust system at work that runs AI agent workflows. All code here is pseudocode.

So we split it


job build(task):
  task.image  = build_image(task.workspace)
  task.status = "built"
  enqueue run_agent(task)

job run_tests(task):
  for shard in task.shards:
    enqueue run_shard(task, shard)
  task.status = "testing"

job run_shard(task, shard):
  run_tests_for(task, shard)
  task.shards_done += 1
  if task.shards_done == task.shards.size:   # two finish at once?
    enqueue open_pull_request(task)

Where does the process live?

clone→ build→ run_agent→ run_tests→ run_shard × N→ open_pr
task.statustask.imagetask.shards_doneretry config × 6idempotency keysa cron that finds stuck rows

Nowhere. It is smeared across six files, a column and a cron.

Questions your job queue can't answer

  • Which step is task 123 on?
  • What did step 2 return?
  • How do I wait three days for a human, then time out?
  • If I cancel now, what must be undone?

Temporal isn't magic here either: its UI shows what ran, not what comes next. To show your users, you write queries.

Other tools exist

IdeaExamples
Queues with batchesSidekiq Pro, GoodJob, Solid Queue
Resumable steps in a jobActiveJob::Continuable, chrono_forge
Process managersRails Event Store
Durable execution enginesRestate, DBOS, Inngest, Hatchet

I haven't researched or verified these. Just pointers.

Act 2

What if the process
was just a method?

Just a method


class AgentWorkflow < Workflow
  def execute(task)
    workspace = activity :clone_repo,  task.repo, timeout: 5.minutes
    image     = activity :build_image, workspace, timeout: 1.hour
    result    = activity :run_agent,   image,     timeout: 3.hours
    pr        = activity :open_pull_request, result

    sleep 3.days                  # really
    activity :ping_reviewers, pr unless activity(:merged?, pr)
  end
end

A worker can die on any line. This still finishes.

Two kinds of code

Workflow

Decides what happens next

  • Must be deterministic
  • No IO, no clock, no random
  • Re-run many times

Activity

Touches the world

  • Just your code
  • API calls, DB, LLM, files
  • Retried, at-least-once

Activities are how you hook in. Everything real is an activity.

Who talks to whom

Your appSDK client Temporal Server Frontend Matching History: the event log Postgres / MySQL / Cassandra Workeryour workflow code Workeryour activities start, query poll tasks results

Temporal never runs your code. Your workers poll it.

First run: every step is written down

dir = activity :clone_repo
img = activity :build_image
res = activity :run_agent
  1. Scheduled clone_repo
  2. Completed clone_repo → "/work/42"
  3. Scheduled build_image
  4. Completed build_image → "img:9f3"
  5. Scheduled run_agent
  6. 💥 workflow worker killed by a deploy

New worker: run the method from the top

dir = activity :clone_repo
img = activity :build_image
res = activity :run_agent
  1. clone_repo: in the log → return "/work/42"
  2. build_image: in the log → return "img:9f3"
  3. run_agent: scheduled, no result → wait

Same code, same inputs, same decisions. Nothing was cloned or built again.

“The system functions via event sourcing: an append-only history of events is stored for each workflow execution, and all required workflow state can be recreated at any time by replaying this history.”

temporalio/temporal, docs/architecture/README.md

You already know these words

Event sourcingTemporal
StreamWorkflow execution history
Command → EventCommand → Event (literally)
Rebuild the aggregateReplay
SnapshotSticky worker cache
Read modelQuery
Process managerWorkflow

One big difference: these events are about execution, not your domain.

The same process, two ways


# Process manager
class AgentProcess
  subscribes_to ImageBuilt, AgentFinished

  def apply(event)
    case event
    when ImageBuilt    then @image  = event.image
    when AgentFinished then @result = event.result
    end
  end

  def act
    return open_pr(@result) if @result
    run_agent(@image) if @image
  end
end

# Workflow
class AgentWorkflow < Workflow
  def execute(task)
    image  = activity :build_image, task
    result = activity :run_agent, image
    activity :open_pr, result
  end
end


# apply/act is still there.
# The language runtime wrote it:
# the stack frame IS the state.

It feels a bit like Haskell

add :: Int -> Int -> Int
save :: Row -> IO ()
  • Haskell: IO changes your type signature, and you can't hide it
  • Temporal: IO changes where your code lives. It must become an activity, on a worker
  • Either way, it reshapes your design. Workflow code is logic only

And in Ruby? TracePoint.


class BadWorkflow < Workflow
  def execute
    Time.now
  end
end
Cannot access Time now from inside a workflow,
reason: Invalid Time.now call.
  • A TracePoint on the workflow thread catches illegal calls
  • A deterministic Fiber::Scheduler runs your coroutines
  • Zeitwerk autoloading trips it in dev: Cannot access File path

I haven't used Temporal in Ruby. This is from the SDK docs and a small test.

Act 3

Now the fun part:
patterns are just code

Prebuild N images, at most 3 at a time


queue = images.dup

lanes = 3.times.map do
  async do
    while (image = queue.shift)
      activity :build_docker_image, image
    end
  end
end

all_of(lanes).wait

An array. No Redis, no semaphore, no lock.

The 3 is now part of your history. Change it to 5 and old runs stop replaying.

React to whichever comes first


fast    = async { activity :cheap_model, prompt }
slow    = async { activity :smart_model, prompt }
timeout = async { sleep 10.minutes; :timed_out }

case first_of(fast, slow, timeout).result
when :timed_out then activity :notify_oncall
else                 activity :save, _1
end
cancel_the_others

The timer is durable. The race survives a deploy.

HITL: human in the loop


class Approval < Workflow
  update def answer(value) = @answer = value
  query  def status        = @answer ? :answered : :waiting

  def execute
    wait_until(timeout: 7.days) { @answer }
    activity(@answer ? :deploy : :escalate)
  end
end

No polling, no cron, no column. Seven days cost nothing.

Errors: classify at the source

What happenedDecision
Timeout, 503, rate limitRetry
Bad URL, invalid cardNon-retryable: stop now
The record is goneSuccess: nothing left to do
Task ran, and the answer is “no”A result, not an error

raise RetryLater.new("rate limited", type: "RateLimited", retry_in: 90.seconds)

Retry defaults will surprise you

  • Default: retry forever. Fine if the activity is idempotent
  • “3 attempts” can be 3 seconds. Waits are 1s, then 2s. The provider is down for 20 minutes. You gave up
  • Failed attempts leave things behind. Half a build, a dirty folder
  • Two kinds of retry. Temporal repeats the activity, or your workflow starts over differently

Poll for results

Submit work to another system. Check once a minute until it's done.


build_id = activity :submit_build, image

def check_build(build_id)           # activity
  raise NotDoneYet unless build_service.status(build_id) == :done
end

activity :check_build, build_id,
  retry: { interval: 1.minute, backoff: 1.0, max_attempts: :unlimited },
  schedule_to_close: 45.minutes     # the real deadline

The retry policy is the wait.

Why fail on purpose?

Loop in the workflow

≈ 11 events

per look: activity, timer, two workflow tasks

45 looks ≈ 495 events

Retries

3 events

Scheduled, Started, Completed, for all attempts together

Retries never land in history

It's Temporal's documented pattern for infrequent polling. The cost: a healthy wait looks like a failing activity.

Sometimes it's just a job queue


class SendEmail < Workflow
  def execute(id) = activity :send_email, id
end

start SendEmail, id: "send-email:#{order_id}", if_running: :use_existing

One workflow, one activity. The id gives you deduplication.

We use Temporal as our background job server.

Schedules: cron that knows what's running


schedule :refresh_images, every: 1.hour, overlap: :buffer_one
Previous run still going?Overlap policy
Drop this tickSkip (default)
Keep one waiting, drop the restBufferOne
Queue them allBufferAll
Stop it and start this oneCancelOther, TerminateOther
Run bothAllowAll

Testing: fake the activities

1. Plain code, no Temporal
  • Logic pulled out of the workflow, i.e. dynamic workflow interpreter
  • Activities faked
  • Fast, hundreds of cases
2a. Real Temporal, fake outside world
  • Real: the workflow and activities, their logic, error mapping, values, timeouts
  • Fake: the external API client
2b. Read the history
  • When the result can't show how it ran
  • Duplicates: 2nd update accepted?
  • Races: in-flight activity cancelled?
  • Retries: which retry policy?
3. End to end
  • All in, all layers
  • Docker images, k8s pods, networking, Temporal, authn & authz, and more
  • The failures no other test can catch
  • Slow as hell

Sleeps in tests? Make durations an input.

My favourite determinism test


Worker.new(max_cached_workflows: 0)
  • No cache: every task replays from the top
  • If it completes, it replayed
  • Completing is the assertion

Rolling a deploy empties the cache anyway. I want that path to be the only path.

Act 4

The bill

Changing a workflow

Code changes. History doesn't. A run in flight must replay on your new code.

Before


activity :build_report
activity :email_report

After


activity :notify_started
activity :build_report
activity :email_report
NondeterminismError: [TMPRL1100] Nondeterminism error:
Activity type of scheduled event 'build_report' does not
match activity type of activity command 'notify_started'
  • Your tests won't catch it: they run only the new code, never old history against it
  • A run lasts a day, a week, a month? Both versions must work that long

So every change gets a patch


if patched?("notify-started")
  activity :notify_started
end
activity :build_report
activity :email_report
  • New runs record a marker. Old runs skip the branch
  • The string is a forever contract. We pin it with a test
  • Replay histories dumped from Temporal in tests, to check old runs still work. Not tried yet

Patches pile up. Removing one: three deploys

1. Old runs still alive


if patched?("notify-started")
  activity :notify_started
end
activity :build_report
activity :email_report

2. Old runs all finished


deprecate_patch("notify-started")
activity :notify_started
activity :build_report
activity :email_report

3. Runs from step 1 finished


activity :notify_started
activity :build_report
activity :email_report
  • Between deploys: wait until the runs started on the previous version are gone
  • Runs last a month? Two months to clean up one if

Or: no patches at all?

  • Worker Versioning (GA in 2026). We don't use it
    • Every deploy of workers is a version: v41, v42…
    • Every run remembers the version it started on
  • Pinned: the run stays on its version until the end
    • No patches
    • Old workers live until their last run ends
    • Week-long runs? A week of v41 next to v42, v43, v44…
    • Rainbow deploys: every version, at once, in production
  • Auto-upgrade: the run moves to the newest workers
    • Old workers can go away
    • New code replays old history, so patches are back

Stop! How do you stop this?

CancelTerminate
Workflow code runs?Yes, if it listensNever
Cleanup possible?If you wrote itNo
Running activity stops?Only if it heartbeatsNo

An activity learns about cancel only from a heartbeat reply.

An agent turn that runs for 2 hours? It finds out in 2 hours.

Async activity

  • A worker restarts during a deploy? The activity runs again
    • Short activity: no pain
    • Long activity: more pain. Split it into smaller chunks, so less is retried
  • Our agent turn
    • Can take long, and you don't know how long: it depends on the prompt
    • Runs somewhere else: the worker starts a K8s pod, the agent works there
    • Can't be split
  • The pattern: the activity starts the work and says "I'll complete later"
    • When the agent is done, it tells Temporal the activity is complete

A word from the sponsor of rock-solid workflows

The Rust SDK

Same Update. Two answers.


class Approval < Workflow
  def execute
    @dm = activity :post_slack_dm    # where the question is
    wait_until { @answer }
  end

  update def answer(value)
    @answer = value
    @dm                              # so we can edit that message
  end
end

Cached worker

answer returns the DM. We edit it

Replay from zero

answer returns nil. The DM never changes

No error, no warning. The one thing you were promised can't happen.

The fix


class Approval < Workflow
  def execute
    @dm = activity :post_slack_dm
    sleep 0.001                      # a timer is a command. sdk-rust#1606
    wait_until { @answer }
  end

  update def answer(value)
    @answer = value
    @dm
  end
end

The step after the activity is no longer empty, so the SDK doesn't merge it on replay.

A 1 ms sleep holding up a durable execution platform.

And now it's in the histories. Removing it needs a patch.

Query says yes. Update says no.

Step 1activity running
The gapactivity done, the workflow hasn't processed the result yet
Step 2waiting for the answer
① Query: is it waiting for the answer? Yessees step 2 → it already counts the activity result
② Update: here's my answer. Rejected: not waitingsees step 1 ← it runs before the activity result

Same workflow, same moment. Two different states.

sdk-rust#1623. In our tests: 3 runs in 8. A human is too slow to hit the gap. Automation isn't.

“The current chunker is complex, brittle, and has already introduced non-determinism.”

Temporal's own PR, temporalio/sdk-rust #1659

Fair play: we're on a pre-1.0 pin from June, 224 commits behind. The SDK has since gone 1.0. It's still open.

Mentally taxing: three goals, four problems

Zero-downtimeBackwards compatibilityIdempotency
Workflow codereplayed after every restartnew code, old histories: patches–
Activity codekilled mid-run by a deployretried: new code, old argumentsruns at least once
Input/activity/update payloads–old JSON for the retention period–
Timeoutsmust outlast a restart–a timeout means a retry

Every small change: check all twelve cells.

Hoops for trivial things


# I want to write one row.
class RecordRunStart < Activity
  def execute(run_id) = db.update(run_id, started_at: now)
end

activity :record_run_start, run_id,
  timeout: 30.seconds, retry: { max_attempts: 5 } if patched?("record-run-start")

One UPDATE: an activity, a timeout, a retry policy, a patch.

Act 5

Now let users write
their own workflows

What we needed

  • Users and LLMs submit a workflow. No deploy
  • Draw it before it runs
  • Show which step we're on
  • Show what values each step computed

Attempt 1: embed a JS engine

user JS→ QuickJS in the workflow→ bridge→ Temporal activity

const files = await session.run("count files")
const doubled = await session.run(`double ${files}`)

It worked. Survived crashes, restarts, replay, cache off.

“Where are we?”


const bugs = (await listIssues(repo)).filter(i => i.labels.includes("bug"))
for (const bug of bugs) {                 // which bug?
  let attempt = 0                         // which attempt?
  let verdict
  do {
    await fix(bug, ++attempt)
    verdict = await review(bug)           // what did the review say?
  } while (!verdict.ok)
}

What would a query even query?

An embedded engine can run the JS. It can't tell you what it is running.

The answers live in VM stack frames. You'd be building a debugger. We never built one.

Flip it: the workflow is data


{ "steps": [
  { "name": "list", "call": "list_issues", "args": { "repo": "input.repo" } },

  { "map": { "in": "steps.list.output.filter(i, 'bug' in i.labels)", "as": "bug",
    "body": [
      { "doWhile": { "cond": "!steps.review.output.ok", "body": [
          { "name": "fix",    "call": "fix",    "args": { "issue": "bug" } },
          { "name": "review", "call": "review", "args": { "issue": "bug" } } ] } }
    ] } }
] }

Structure: JSON. Leaves: CEL.

The interpreter is one workflow


class InterpreterWorkflow < Workflow
  query def progress = @progress

  def execute(plan, input) = walk(plan.steps, Env.new(input))

  def walk(steps, env)
    steps.each do |step|
      case step
      when Call
        args = Cel.eval(step.args, env)   # right here, in the workflow
        @progress[step.path] = :running
        env.steps[step.name] = activity(step.op, args)
        @progress[step.path] = :done
      when If then walk(Cel.eval(step.cond, env) ? step.then : [], env)
      end
    end
  end
end

Why CEL fits a workflow

steps.list.output.filter(i, 'bug' in i.labels)
  • Common Expression Language, from Google. No IO, no clock, no mutation
  • Can't break replay. There's no Date.now to call
  • Runs in Kubernetes admission, Cloud IAM, Envoy, Firebase rules
  • LLMs know it, and parse errors teach them
  • Seven implementations: Go, C++, Java from Google. Rust, Python, JS/TS, Ruby from the community

Now the query just works

listdone7 issues, 4 bugs
bug 1donereview ok after 1 attempt
bug 2donereview ok after 2 attempts
bug 3 · attempt 3 · fixrunninglast review: "tests fail"
bug 4pending

Step identity = path + loop iteration. Rebuilt by replay, for free.

How hard is it to show?

DAGBoxes and arrows. GitHub Actions, Airflow, most workflow engines
+ LoopsOne step, shown many times: bug 3, attempt 3
+ ParallelismMany iterations running at once. Which one is "now"?
Any async codePromise.all, race, any, allSettled, for await, AbortController, fire-and-forget, a semaphore… Each needs its own syntax and its own picture

Our DSL stops at parallel map. Every step up needs a new picture.

What it looks like

Progress view of a running workflow: finished steps, two parallel research roles done, three parallel reviews running, and the files each step saved or pulled in

Still not free

  • Non-Turing-complete ≠ bounded: a few hundred bytes of nested .all(), tens of seconds
  • “Pure” can still vary: a hash map had to get sorted keys
  • Bad reference? Not a parse error. Fails at run time
  • User text is an attack surface, and it runs in your worker

No conclusion.
Just what stayed with me.

pankowecki.pl · github.com/paneq

A different way of thinking

  • The log is the truth. The running code is a projection of it
  • Log-based truth, reached from the problem, not the pattern
  • Time is just another thing that happens
  • Crash stops being a special case

Appendix

Real Ruby, for the questions

gem temporalio 1.10.1, on the SDK test server. Not something I use at work

Workflow, activity, retries


class Charge < Temporalio::Activity::Definition
  def execute(amount)
    raise Temporalio::Error::ApplicationError.new(
      'card declined', type: 'CardDeclined', non_retryable: true) if amount < 0
    "charged #{amount}"
  end
end

class ChargeWorkflow < Temporalio::Workflow::Definition
  def execute(amount)
    Temporalio::Workflow.execute_activity(Charge, amount,
      start_to_close_timeout: 30,
      retry_policy: Temporalio::RetryPolicy.new(
        initial_interval: 1, backoff_coefficient: 2.0, max_interval: 60,
        max_attempts: 5, non_retryable_error_types: ['InvalidCard']))
  end
end

Bounded parallelism, race


W = Temporalio::Workflow

slots = W::SizedQueue.new(limit)
futures = items.map do |item|
  W::Future.new do
    slots.push(true)
    begin
      W.execute_activity(Work, item, start_to_close_timeout: 30)
    ensure
      slots.pop
    end
  end
end
W::Future.all_of(*futures).wait

cancellation, cancel = Temporalio::Cancellation.new(W.cancellation)
act   = W::Future.new { W.execute_activity(Work, 1, start_to_close_timeout: 30, cancellation:) }
timer = W::Future.new { W.sleep(3600, cancellation:); :timeout }
W::Future.any_of(act, timer).wait
cancel.call

Cancel with cleanup, test a week


def execute
  W.sleep(3600)
rescue Temporalio::Error => e
  raise unless Temporalio::Error.canceled?(e)
  W.execute_activity(Cleanup, start_to_close_timeout: 30,
                     cancellation: Temporalio::Cancellation.new) # detached
  raise
end

Temporalio::Testing::WorkflowEnvironment.start_time_skipping do |env|
  # a workflow sleeping for a day finishes right away
end

require 'temporalio/worker/workflow_replayer'
Temporalio::Worker::WorkflowReplayer.new(workflows: [MyWorkflow])
  .replay_workflow(handle.fetch_history)

Limits to remember

LimitWarnsFails
History events10,24051,200
History size10 MB50 MB
Single payload512 KB2 MB
Pending activities or children2,000

Polling guide: under 1s, loop in an activity and heartbeat. Over 1 min, use retries. Complex: child workflow and Continue-As-New.

Reading list