Temporal to follow onchain blocks

One scanner per network that lives forever, remembers where it stopped and takes orders. No cron, no flag in the database, no script at dawn.

Listening to a blockchain is an infinite loop

A blockchain is a queue of blocks that never stops growing. Inside each block there are transactions, and inside them, events: an ERC-20 contract emits Transfer(from, to, value) every time tokens change hands. If you want to know when a set of addresses receives tokens, there is no place to "subscribe". You walk the blocks, one range at a time, ask the node for the logs of that range and write down how far you have looked.

12001201120212031204120512061207120812091210121112121213already read: events storedcursornext range: 1206 to 1210marginconfirmations: waitheadreported by the nodethe cursor only moves once the range's events are stored; the margin avoids reading blocks that may still change
The whole state of the scanner fits in one number: the next block to read. The job is keeping it right forever.

The classic way, and where it cracks

Everyone's first version is a cron calling a script, with a database row holding the last block. It works on a quiet Sunday. The rest of the week shows up in pieces:

What happensWhat you end up writing
The process dies in the middle of a rangeLogic to not duplicate or skip a block, and hoping the deploy does not land right there.
A tick takes longer than the cron intervalA lock in the database or in Redis so two scanners do not run together.
The RPC node times outRetry with backoff, by hand, on every call.
You need to stop a networkA flag in the table and an if everywhere.
You need to reprocess from block XA script at dawn that edits the cursor row by hand.
"Which block is the Polygon scanner on?"Open the database, read the row and trust that the process is alive.

Every row of this table is a piece of infrastructure that has nothing to do with blocks. The real problem was always something else: the scanner is a process that needs to live forever, remember where it stopped, survive crashes and take orders while it runs.

The idea in one sentence: that is the description of a Temporal workflow. The state lives in the function itself; the server keeps the history; if the worker dies, another one picks up from the same point; signals come in while it runs; a query answers where it is. All that is left for you to write is the part about blocks.

What Temporal changes

A Temporal workflow is ordinary code, with one odd property: it can be interrupted and resumed at any point, even on another machine, without losing its local variables. The server records each step (an activity that finished, a timer that fired, a signal that arrived) in an event history. When a worker picks the workflow back up, it re-runs the function reading that history, and the variables come back to the same values. The function never notices it went down.

Worker Acursor = 1206scan... dies halfwayTemporal serverevent historyActivityCompletedTimerFiredSignalReceivedActivityScheduledWorker Bcursor = 1206scan... carries on from the same pointsavesreplaythe function never knew it went down: local variables are rebuilt from the history
For this to work, the workflow has to be deterministic: no network, database or clock inside it. All of that goes into activities.

This split between workflow (the orchestration, deterministic, rebuildable) and activity (the call to the real world, with retry) is the whole rule. In the scanner, the activity is "read range X to Y and store what you found". The workflow decides when to call it, how long to sleep, when to stop.

Next: the design, piece by piece →

Two pieces

The whole design has two kinds of workflow. A short supervisor, fired by a Temporal schedule every few minutes, that only checks what should be running. And a long scanner per network, which never ends on its own.

Scheduleevery 5 minSupervisorlasts secondsNetwork registryethereum, polygon, basereadsensures one per networkscanner-ethereumlong-lived workflow, fixed idread → store → sleep ↺scanner-polygonlong-lived workflow, fixed idread → store → sleep ↺scanner-baselong-lived workflow, fixed idread → store → sleep ↺the supervisor does not do the work; it only makes sure whoever does it is alive
The scanner's id is the network's name. That alone is enough for the supervisor never to create two.

The scanner loop

Inside the scanner, life is simple. It calls the read activity passing the cursor; the activity reads up to the chain's safe head, stores the events and the new cursor, and returns the next block. If there are still blocks behind, it reads again right away. If it caught up with the head, it sleeps a tick. At any point a signal may arrive.

1. read rangeactivity, with retry2. move cursorin workflow memory3. caught up with head?no: back to 14. sleep a tickserver timeryeswoke up (or a signal arrived): againsignal: stopsignal: rescan_fromquery: statusonly reads, does not interrupt
The "sleep" timer belongs to the server, not to the process. A worker can die and come back ten times during a tick; the timer fires anyway.

The cursor lives in two places

The cursor is a workflow variable. That already makes it durable: it is in the history and survives any crash. Even so, the activity also writes the cursor to a table, together with the events, in the same transaction. The two places play different roles.

WhereWhat forWho reads it
Workflow stateIt is the real cursor while the scanner runs. It decides the next range.The loop itself, the status query.
Database tableStarting point when the scanner is created from scratch (first time, or after a stop). Visible to humans and reports.The supervisor, when starting a scanner.

Writing the cursor and the events in the same transaction is what makes the scanner safe against a crash halfway: either the whole range went in with the new cursor, or nothing went in and the activity runs again with the old cursor. And since each event is stored by (tx_hash, log_index) with an upsert, reading the same block twice creates nothing twice.

Continue-as-new: the history does not grow forever

Each turn of the loop adds a few events to the history: activity scheduled, activity completed, timer started, timer fired. A scanner that has been running for months would have a history of millions of events, and replay would get slower and slower. Temporal solves this with continue-as-new: the workflow ends the current run and starts another, with the same id, passing as input only what matters. Here, the network name and the cursor.

scanner-polygonrun 1history: 9,800 eventsscanner-polygonrun 2history: 9,800 eventsscanner-polygonrun 3history: 3 eventscursorcursorsame id, signals and queries keep arriving at the same address; from outside nobody notices the swap
The SDK tells you when it is time (continue_as_new_suggested). The scanner only needs to check it once per turn.

Signals and query: talking to the live process

Since the scanner is a workflow with a known id, any client can send it messages without knowing which machine it is on. Three are enough:

MessageKindWhat it does
stopsignalSets a flag. The loop finishes the read in progress and exits cleanly. No database row to "turn off".
rescan_from(block)signalMoves the cursor back. The next turns reread the stretch; the upsert ensures nothing is duplicated. Useful for a reorg deeper than the margin, or for a new address that needs history.
statusqueryAnswers network, cursor and state, reading the workflow variables. It changes nothing and does not interrupt the loop.

A signal arrives during the "sleep"? The scanner wakes up right away: the wait is "until the tick or until a signal arrives". A signal arrives during the read? It is kept and applied as soon as the activity returns.

The supervisor is idempotent

The supervisor does one thing only: for each network in the registry, if there are watched addresses, it asks Temporal to start scanner-<network> with the policy "if it already exists, use the one that is there". If there are no more addresses and the scanner is running, it sends stop. Running the supervisor twice in a row changes nothing. Turning on a new network means adding a line to the registry; the supervisor's next tick creates the scanner. No deploy, no new cron.

Play with the scanner

A small model of the loop, with no network or database. Press the buttons and see what happens to the cursor, the state and the history.

workflow
scanner-polygon
state
running
cursor
64 120 000
safe head
64 120 040
run
1
events in history
1

    What you get for free

    Cron worryWho handles it now
    Process dies halfwayHistory replay: the run carries on from the same point on another worker.
    Two scanners at the same timeUnique id per network + conflict policy. The server refuses the second one.
    Flaky RPCThe activity's retry policy, with backoff, set in one line.
    Stopping a networkThe stop signal. Turning it back on is the supervisor on its next tick.
    Reprocessing from XThe rescan_from(X) signal.
    Where is the scanner?The status query, or the Temporal UI, which shows every run and every event.
    A tick that takes longer than the intervalThere is no fixed interval: the scanner reads until it catches up with the head and only then sleeps.

    Next: the code, in Ruby →

    The example

    ERC-20 transfers to a set of watched addresses, on three EVM networks, with Temporal's Ruby SDK (temporalio). The model names (WatchedAddress, Transfer, ScanCursor) are what you would expect. The code is illustrative and leaves out what is not the topic: RPC authentication, ABI decoding, metrics.

    The network registry

    # A plain hash is enough: one entry per chain the platform follows.
    # Adding a chain here is all it takes; the supervisor picks it up on its next tick.
    CHAINS = {
      "ethereum" => { rpc: ENV["ETH_RPC"],  confirmations: 12, tick: 45, batch: 2_000 },
      "polygon"  => { rpc: ENV["POLY_RPC"], confirmations: 64, tick: 30, batch: 5_000 },
      "base"     => { rpc: ENV["BASE_RPC"], confirmations: 20, tick: 30, batch: 5_000 },
    }.freeze

    The activity: the only place that talks to the world

    It takes the cursor, computes the safe head, reads a batch of blocks, stores events and cursor in the same transaction and returns the next block. It is short and has no state of its own, so it can be retried at will.

    class ScanRange < Temporalio::Activity::Definition
      # Reads one range of blocks and persists what it found.
      # Everything that touches the network or the database lives here,
      # never in the workflow.
      def execute(chain, from_block)
        cfg  = CHAINS.fetch(chain)
        rpc  = JsonRpc.new(cfg[:rpc])
        # safe head: reorgs below it are rare
        head = rpc.block_number - cfg[:confirmations]
        to   = [from_block + cfg[:batch] - 1, head].min
        return { next_from: from_block, caught_up: true } if to < from_block
    
        watched = WatchedAddress.where(chain: chain).pluck(:address)
        logs = rpc.get_logs(
          from_block: from_block, to_block: to,
          # Transfer(from, to, value): filter by the "to" topic
          topics: [TRANSFER_TOPIC, nil, watched.map { |a| pad32(a) }],
        )
    
        Transfer.transaction do
          logs.each do |log|
            # Idempotent: the same log can arrive twice (retry, rescan)
            # and still count once.
            Transfer.upsert(decode(log), unique_by: %i[tx_hash log_index])
          end
          ScanCursor.upsert({ chain: chain, next_block: to + 1 }, unique_by: :chain)
        end
    
        { next_from: to + 1, caught_up: to == head }
      end
    end

    The scanner

    Notice what is not here: no network call, no database, no Ruby sleep. Everything that touches the world goes through execute_activity; the wait is a server timer that a signal can interrupt.

    class ScannerWorkflow < Temporalio::Workflow::Definition
      # One long-lived run per chain. Loops forever: scan, move the cursor, sleep, repeat.
    
      workflow_signal
      def stop
        @stop = true
      end
    
      workflow_signal
      def rescan_from(block)
        @cursor = block
      end
    
      workflow_query
      def status
        { chain: @chain, cursor: @cursor, state: @stop ? "stopping" : "running" }
      end
    
      def execute(chain, cursor)
        @chain, @cursor = chain, cursor
        tick = CHAINS.fetch(chain)[:tick]
    
        loop do
          result = Temporalio::Workflow.execute_activity(
            ScanRange, chain, @cursor,
            start_to_close_timeout: 120,
            retry_policy: Temporalio::RetryPolicy.new(initial_interval: 2, max_interval: 60),
          )
          # A rescan_from that arrived during the scan wins over the activity result.
          @cursor = result[:next_from] if @cursor <= result[:next_from]
    
          return status if @stop
          # The event history grows every loop; hand over to a fresh run with the same id.
          if Temporalio::Workflow.continue_as_new_suggested
            raise Temporalio::Workflow::ContinueAsNewError.new(chain, @cursor)
          end
    
          next unless result[:caught_up]
          # Sleep until the next tick, but wake up early for a signal.
          begin
            Temporalio::Workflow.wait_condition(timeout: tick) do
              @stop || @cursor < result[:next_from]
            end
          rescue Timeout::Error
            # no signal: just the next tick
          end
        end
      end
    end
    Why the cursor compares before accepting the result: if a rescan_from arrived while the activity was reading, the in-memory cursor ended up lower than the returned next_from. In that case the signal wins, and the next turn rereads from it. Without the comparison, the activity result would overwrite the signal and the rescan would be lost.

    The supervisor

    A workflow with a single activity. The activity uses the Temporal client to ensure each network's scanner, and it is idempotent by construction: USE_EXISTING turns start_workflow into a no-op when the scanner is already running.

    class SuperviseScanners < Temporalio::Activity::Definition
      # Runs from the schedule. Idempotent: calling it twice changes nothing.
      def execute
        client = Temporalio::Client.connect("localhost:7233", "default")
    
        CHAINS.each_key do |chain|
          handle = client.workflow_handle("scanner-#{chain}")
    
          if WatchedAddress.exists?(chain: chain)
            cursor = ScanCursor.find_by(chain: chain)&.next_block || client_head(chain)
            client.start_workflow(
              ScannerWorkflow, chain, cursor,
              id: "scanner-#{chain}", task_queue: "scanners",
              # Already running? Keep the existing run. No duplicates, ever.
              id_conflict_policy: Temporalio::WorkflowIDConflictPolicy::USE_EXISTING,
            )
          elsif running?(handle)
            handle.signal(ScannerWorkflow.stop)     # nobody is watching this chain anymore
          end
        end
      end
    end
    
    class SupervisorWorkflow < Temporalio::Workflow::Definition
      def execute
        Temporalio::Workflow.execute_activity(SuperviseScanners, start_to_close_timeout: 60)
      end
    end

    The schedule and the worker

    # Once, at deploy time. The schedule survives restarts; the server owns the clock.
    client.create_schedule(
      "scanner-supervisor",
      Temporalio::Client::Schedule.new(
        action: Temporalio::Client::Schedule::Action::StartWorkflow.new(
          SupervisorWorkflow, id: "scanner-supervisor", task_queue: "scanners",
        ),
        spec: Temporalio::Client::Schedule::Spec.new(
          intervals: [Temporalio::Client::Schedule::Spec::Interval.new(every: 300)],
        ),
        policy: Temporalio::Client::Schedule::Policy.new(
          overlap: Temporalio::Client::Schedule::OverlapPolicy::SKIP,
        ),
      ),
    )
    
    # The worker that runs all of it.
    Temporalio::Worker.new(
      client: client, task_queue: "scanners",
      workflows: [SupervisorWorkflow, ScannerWorkflow],
      activities: [SuperviseScanners, ScanRange],
    ).run

    Operating it

    handle = client.workflow_handle("scanner-polygon")
    
    handle.query(ScannerWorkflow.status)
    # => { chain: "polygon", cursor: 64_120_311, state: "running" }
    
    handle.signal(ScannerWorkflow.rescan_from, 64_100_000)   # replay 20k blocks, no duplicates
    handle.signal(ScannerWorkflow.stop)                       # finishes the current scan and exits

    Details that make a difference

    1. The confirmations margin is the first defense against reorgs. The scanner never reads the last N blocks. For the rare reorg deeper than that, rescan_from rereads the stretch and the upsert absorbs what already existed.
    2. Bounded batch. A new scanner on a network with millions of blocks behind does not ask for everything at once: it reads batch blocks per activity, without sleeping in between, until it catches up with the head. A short activity is easy to retry; a giant one hits the timeout.
    3. Timeout and retry in the activity, not in the code. start_to_close_timeout kills a stuck call; the retry policy tries again with backoff. The RPC can be down for an hour and the scanner will just look late.
    4. Determinism in the workflow. No Time.now, rand, mutable globals or I/O. The network registry is constant and can be read; the database cannot.
    5. Schedule with SKIP. If the previous supervisor is still running when the next one fires, the new one is skipped. Never two supervisors at the same time.
    6. The id is the API. scanner-polygon is all an operations script needs to know to ask, pause or request a rescan.

    What is left out of this design

    The RPC provider's rate limit (solved with the batch size and the per-network tick), non-EVM networks (each one becomes a registry entry with its own read activity, but the scanner and the supervisor stay the same), and what to do with each event once stored, which is the job of the rest of the system, not of the scanner.

    The idea in one sentence, again: following blocks is a loop that needs to live forever, remember where it stopped and take orders. Temporal does the "live forever" part; your code only says what to do with each range.

    ← Back to the problem