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.
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 happens | What you end up writing |
|---|---|
| The process dies in the middle of a range | Logic to not duplicate or skip a block, and hoping the deploy does not land right there. |
| A tick takes longer than the cron interval | A lock in the database or in Redis so two scanners do not run together. |
| The RPC node times out | Retry with backoff, by hand, on every call. |
| You need to stop a network | A flag in the table and an if everywhere. |
| You need to reprocess from block X | A 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.
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.
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.
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.
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.
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.
| Where | What for | Who reads it |
|---|---|---|
| Workflow state | It is the real cursor while the scanner runs. It decides the next range. | The loop itself, the status query. |
| Database table | Starting 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.
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:
| Message | Kind | What it does |
|---|---|---|
stop | signal | Sets a flag. The loop finishes the read in progress and exits cleanly. No database row to "turn off". |
rescan_from(block) | signal | Moves 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. |
status | query | Answers 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 worry | Who handles it now |
|---|---|
| Process dies halfway | History replay: the run carries on from the same point on another worker. |
| Two scanners at the same time | Unique id per network + conflict policy. The server refuses the second one. |
| Flaky RPC | The activity's retry policy, with backoff, set in one line. |
| Stopping a network | The stop signal. Turning it back on is the supervisor on its next tick. |
| Reprocessing from X | The 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 interval | There is no fixed interval: the scanner reads until it catches up with the head and only then sleeps. |
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 },
}.freezeThe 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
endThe 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
endrescan_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
endThe 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],
).runOperating 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 exitsDetails that make a difference
- 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_fromrereads the stretch and the upsert absorbs what already existed. - Bounded batch. A new scanner on a network with millions of blocks behind does not ask for everything at once: it reads
batchblocks 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. - Timeout and retry in the activity, not in the code.
start_to_close_timeoutkills 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. - 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. - 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. - The id is the API.
scanner-polygonis 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.
