Home / Notes

Reference architecture: real-time chain data for DeFi and trading

2026-10-30 · Web3 data · Edward Plata

A trading desk, a market maker or a DeFi risk team cannot wait for an hourly batch. They need chain events in seconds, next to exchange prices. They also need those events to be correct when the chain reorgs. This note gives a reference design for that system, including the join with centralized exchange (CEX) data.

This is a reference design. It is not a DataBlock client case study. The streaming pattern I have built before is simpler: Kafka between a public HTTP endpoint and Postgres, described in the WeMeta field report. That pipeline carried in-world events, not chain data.

Start with the latency budget

Start with the chain, not a target such as "under one second". The chain decides how often new data exists. Each hop adds delay.

Block times set the floor:

  • Ethereum. "Time in proof-of-stake Ethereum is divided into slots (12 seconds) and epochs (32 slots)", per ethereum.org.
  • Base. Base's docs say: "You can move from 2-second block confirmations to 200ms pre-confirmations by switching one URL and one block tag."
  • Solana. Slots "occur approximately every 400 milliseconds", per the solana-clock crate docs.

After block production, each hop adds its own delay. I have no sourced end-to-end figure for any stack. Use this template and measure each hop in your own system.

HopWhat sets the delayHow to measure it
Block producedChain block or slot timeBlock timestamp or slot number
Seen by your sourceNode sync, network path, providerSource receive time minus block time
DecodedABI lookup, decoder speedDecoder output time minus receive time
In the busProducer batching, brokerBroker append time minus decode time
In the storeSink batching, insert sizeInsert time minus broker time
QueryableMerges, views, cachesFirst successful query time minus insert time

Log one timestamp per hop on every message. A lag dashboard per hop shows where to spend effort.

Stream sources, from most control to least

More control means more operations work.

 BLOCK TIME          SOURCE                        BUS
 Ethereum 12 s  ──► node: eth_subscribe        ─┐
                    or Reth ExEx                │
 Base 2 s       ──► Substreams                  ├──► Kafka or Redpanda
  (~200 ms pre-     (cursor + undo signal)      │    one topic per
   confirmations)   Goldsky Turbo               │    chain and entity
 Solana ~400 ms ──► Geyser plugin or            │
  slots             Yellowstone gRPC           ─┘
 CEX websockets ──► normaliser ────────────────────► trades, books

Your own node with eth_subscribe. This is the simplest EVM source. You subscribe to newHeads and logs. Reorgs arrive as repeats. Geth's docs say that on a reorg, old logs "will be resent with the removed property set to true", and "a subscription can emit logs for the same transaction multiple times." newHeads "can emit multiple headers on the same height." A dropped websocket also leaves a gap to backfill.

Reth Execution Extensions (ExEx). An ExEx runs inside the node. Reth's docs say ExExes "are compiled into the same binary as Reth, and run alongside it, using shared memory for communication." Paradigm's post says it "exposes a ChainCommitted variant for appending to ExEx state and a ChainReverted/Reorged-variant for undoing any changes." The ExEx reports progress with ExExEvent::FinishedHeight, which Reth uses "to determine what state can be pruned." A slow ExEx therefore holds back pruning, and disk use grows. To use an ExEx, you must run Reth and write Rust.

Substreams. Substreams handles backfill and live data with one cursor. On a reorg it sends a BlockUndoSignal that "contains the latest valid block of the blockchain and a cursor". Its docs say the user "must persist the cursor". The cursor must be saved in the same transaction as the output. A database sink can do that. A Kafka sink cannot, so delivery through Kafka is at-least-once and needs idempotent keys downstream. The SQL sink writes to "Postgres or ClickHouse".

Goldsky Turbo is a managed pipeline. Turbo sinks include PostgreSQL, ClickHouse, MySQL, Kafka, S3, SQS, webhooks and others.

Solana: Geyser and Yellowstone. A Geyser plugin runs inside a validator or RPC node. It receives "information about accounts, slots, blocks, and transactions". The Anza docs carry a warning: the plugin "should process the notification as fast as possible because any delay may cause the validator to fall behind the network." Yellowstone gRPC is a Geyser plugin that serves a gRPC stream. It streams "slots, blocks, transactions, deshred pre-execution transactions, and account update notifications", with commitment levels processed, confirmed and finalized.

Hosted versions exist, such as Helius LaserStream.

An in-house block store. Coinbase published ChainStorage, which "acts like a distributed file system for the blockchain." Coinbase says it "can serve up to 1,500 blocks per second" in its own production setup. That is throughput, not latency. The README says: "If you want the most up-to-date blocks, you need to use the streaming APIs to handle the chain reorg events."

Feeds also change. Jito's docs announced a shutdown of its ShredStream service for September 5, 2026. I have not checked its status since. Design so you can replace a source without downstream changes.

The bus

Put Kafka or Redpanda between sources and stores when you have several consumers, need replay, or join chain and CEX data. Redpanda says it is "compatible with the Kafka API" (docs).

Use one topic per chain per entity: blocks, logs, decoded swaps, account updates.

Kafka orders messages only within one partition. If you key swaps by pool, an undo for block N on one partition can arrive after data for block N on another. Pick one of two fixes:

  • One partition key per chain for raw and undo messages, with one writer. Order then holds, but you lose parallelism.
  • Order-independent sinks. Every row carries block_hash and a version, and the sink deletes by block range on undo. Late data for an orphaned hash is then dropped on arrival.

Enable the idempotent producer, and commit consumer offsets only after the sink write succeeds. That gives at-least-once delivery. The idempotent keys below absorb the duplicates. Serialize with a schema format such as Avro or Protobuf, and keep schemas in a registry.

Every message carries one envelope:

chain_id, block_number, block_hash, parent_hash,
tx_index, log_index, event_id, schema_version,
commitment, is_undo, source_ts, decode_ts, payload

The dedup key is (chain_id, block_number, tx_index, log_index). It leaves out block_hash on purpose. A row from an orphaned block then collides with its replacement, and the replacement wins. parent_hash lets an eth_subscribe consumer detect reorgs itself.

If you have one source and one sink, skip the bus. Substreams and Goldsky can write straight to Postgres or ClickHouse.

Reorgs in a stream

Each source reports reorgs in its own way:

SourceHow it reports a reorgWhat the consumer must do
Geth logsRe-sends old logs with removed: trueDelete those rows by key; on reconnect, re-check recent hashes
Reth ExExChainReorged or ChainRevertedUndo the old range, apply the new
SubstreamsBlockUndoSignal with last valid blockDelete above that block, save cursor
Goldsky TurboCorrection recordsUpserts and deletes, or apply them yourself
Solana streamsCommitment levels and slot statusDelete rows from dead slots; use finalized for settlement

Goldsky's delivery guarantees page says "Turbo pipelines are reorg-aware end to end", but "For append-only destinations (Kafka, S3, webhooks), your consumer sees the correction records and must apply them itself." It also says "Turbo does not provide exactly-once delivery."

ChainStorage's README shows the model every consumer must apply: events +1, +2, +3, -3, -2, +2', +3' give the canonical chain +1, +2', +3'.

The design rule: every message has a block number and a block hash. Every sink can delete or replace rows by block. Every row records its commitment level. The note on reorgs and finality goes deeper.

Two cases need extra rules. First, removed: true notices exist only on a live connection. A reorg during a websocket drop is never announced. On reconnect, fetch the last N blocks, where N is the deepest reorg you accept, and compare their hashes to stored rows before you resume. Second, Solana data at processed can belong to a fork that the cluster abandons. Consume slot status updates, key rows by slot and blockhash, and delete rows from dead slots. Do not promote them. Solana slot numbers and block heights also differ, so store both.

For money, act on finalized for settlement and accounting. Use confirmed or processed only for signals that accept rollback risk. Helius says: "Use processed for the earliest delivery and confirmed once you need a level of finality that won't roll back."

Serving: ClickHouse and Postgres

             Kafka or Redpanda
        │            │              │
        ▼            ▼              ▼
  HOT: ClickHouse  STATE: Postgres  COLD: lakehouse
  ReplacingMerge-  upsert by key,   Delta or Iceberg,
  Tree(ver,        delete by block  replay and
  is_deleted)      on undo          reconcile
        │            │
        └─────┬──────┘
              ▼
  APIs, dashboards, signals, risk checks
  as-of join of chain events and CEX trades

ClickHouse is the hot store for time-series scans: swaps per pool per minute, volume by venue, liquidations by block. Duplicates will arrive, because the common paths are at-least-once. ClickHouse's Kafka page lists "At-least-once semantics" for the Kafka table engine and ClickPipes, and "Exactly-once semantics" for the Kafka Connect Sink.

Use ReplacingMergeTree with a version column and an is_deleted flag. Its docs say "Data deduplication occurs only during a merge", so queries that must be correct use FINAL. is_deleted "can only be enabled when ver is used." FINAL is slow on large data, so limit it to a block range or a recent partition, or read argMax aggregates. When tombstone rows are physically removed depends on the ClickHouse version and settings.

-- Illustrative only.
CREATE TABLE hot.swaps
(
  chain_id     UInt32,
  block_number UInt64,
  block_hash   FixedString(32),       -- raw bytes, not hex text
  tx_index     UInt32,
  log_index    UInt32,
  pool         LowCardinality(String),
  pair         LowCardinality(String),
  block_ts     DateTime64(3),
  amount_in    UInt256,               -- full uint256 range
  amount_out   UInt256,
  commitment   LowCardinality(String),
  ver          UInt64,                -- ingest sequence, see below
  is_deleted   UInt8
)
ENGINE = ReplacingMergeTree(ver, is_deleted)
PARTITION BY toYYYYMM(block_ts)
ORDER BY (chain_id, block_number, tx_index, log_index);

ver is a sequence number that only grows, such as an ingest counter or the Kafka offset of a single-partition topic. A later write always beats an earlier one for the same key. Block number does not work as ver, because the replacement row has the same block number.

A reorg takes two steps. An undo signal such as BlockUndoSignal gives only the last valid block. So the writer first selects the keys stored above that block. Then it inserts one row per key with a higher ver and is_deleted = 1.

The sort key serves dedup, so it does not serve per-pool or time queries. Add a projection or a second table sorted by (pool, block_ts) for those.

Be careful with rollups. A materialized view or SummingMergeTree that sums swaps at insert time never sees dedup or tombstones. It will double count and keep orphaned volume. Build rollups from finalized blocks only, or rebuild the reorg window from the deduplicated table on each run.

Postgres holds small, mutable state: open positions, latest pool reserves, alert rules. It applies an undo inside a transaction. That is simpler to reason about than background merges. Guard every upsert with the version, so a replayed old message cannot overwrite newer state: ON CONFLICT (...) DO UPDATE SET ... WHERE excluded.ver > t.ver.

The cold path. Everything on the bus also lands in the lakehouse described in the lakehouse reference architecture. The stream is for speed. The lake is for replay, backfill and reconciliation. Once blocks are finalized, compare row counts and block hashes per block between the hot store and the lake. On a mismatch, re-apply that block from the lake.

Joining chain data with CEX market data

Join on event time, not arrival time. Chain time is the block timestamp. CEX time is the exchange's trade or book timestamp. Arrival times measure your network. Both clocks have limits. The block proposer sets the block timestamp, in 12-second steps on Ethereum. Exchanges set their own timestamps. Pair names also differ (WETH/USDC on chain, ETH/USDT on an exchange), so map pairs and apply token decimals before you compare prices.

Use an as-of join: for each chain event, take the latest CEX trade at or before the block timestamp, within a window. Keep both timestamps and the commitment level.

-- Illustrative only. ClickHouse ASOF JOIN with a 5 s window.
SELECT s.block_number, s.pool, s.amount_in, s.amount_out,
       t.price AS cex_price
FROM (
  SELECT block_number, pool, pair, block_ts, amount_in, amount_out
  FROM hot.swaps FINAL  -- dedup; FINAL drops is_deleted rows
  WHERE block_ts >= now() - INTERVAL 1 HOUR
) AS s
ASOF JOIN (
  SELECT pair, trade_ts, price
  FROM hot.cex_trades
  WHERE trade_ts >= now() - INTERVAL 1 HOUR  -- bound the right side
) AS t
  ON s.pair = t.pair AND s.block_ts >= t.trade_ts
WHERE t.trade_ts >= s.block_ts - INTERVAL 5 SECOND;

ClickHouse ASOF takes equality plus one inequality in ON, so the window goes in WHERE. Apply pair mapping and decimals before comparing prices.

Recompute recent windows when late data arrives: sealed Base blocks, promoted Solana rows, CEX gap fills. The market data lakehouse page covers the batch side of this join.

Failure modes

FailureHow the design handles it
EVM reorgBlock hash on every row; delete or tombstone by block
Solana dead slotDelete rows from abandoned slots; promote surviving rows
L2 head changesLabel Base pre-confirmed rows preconfirmed; store the block tag used
Websocket drop or RPC gapBackfill the gap by range; re-check the last N block hashes
Duplicates after restartIdempotent keys; ReplacingMergeTree with ver
Slow consumerKeep the first hop thin; buffer in the bus; alert on lag
Contract upgradeKeep a raw topic; re-decode from it (see decoding)
Feed or vendor shutdownThe bus is the contract; swap the source behind it

What to build first

  1. One chain and one source.
  2. One raw topic with the full envelope.
  3. One ClickHouse table with ver, is_deleted and a working undo path.
  4. A lag metric for every hop in the budget table.
  5. A test that injects a fake reorg and checks the table afterwards.
  6. The cold path into the lakehouse.

Add chains, sources and CEX feeds after that test passes. The Rust ingestion and indexers page covers the ExEx and Geyser side. The Web3 data service covers the full scope.

If you need chain events next to exchange data in seconds, with reorgs handled, I can review your design or build the first pipeline with you.

Book a 30-minute call

Ask a question