> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blockdb.chaintable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 实时订阅

> 使用 Subscribe 订阅区块写入事件，构建实时的增量消费管道。

# 实时订阅

当一个 Block 表有新块写入，BlockDB 会通过 Kafka 发布一个区块订阅事件。SDK 的 `Subscribe` 负责消费这个事件流，把下游业务接在区块"心跳"上，构建"生产 → 事件 → 消费"的闭环。

## 基本用法

订阅一张 Block 表，逐块消费：

```python theme={null}
from blockdb import BlockTable
from blockdb.block_table import Subscribe

t = BlockTable("token.token.eth")

for table_id, block in Subscribe(tables=[t]).listen():
    print(table_id, block.height, block.id)
    # 用 block 读取该块数据、触发下游计算
```

`listen()` 是一个长驻生成器，每次 yield `(table_id, block)`。`block` 是 `Block` 数据单位（`id` / `height` / `timestamp`）。

## 多表订阅

订阅多张表时，事件按表分发，`table_id` 用来区分来源。同一张表重复传入会被去重：

```python theme={null}
a = BlockTable("token.token_transfer.eth")
b = BlockTable("address.addresses.eth")

for table_id, block in Subscribe(tables=[a, b]).listen():
    print(table_id, block.height)
```

## 指定起始游标

默认从最新开始订阅。用 `start_at` 指定起始游标，从某个时间之后的事件开始消费：

```python theme={null}
sub = Subscribe(tables=[t], start_at="2026-08-17T00:00:00Z")
```

`start_at` 接受 RFC3339 时间字符串（如 `2026-08-17T00:00:00Z`）或 epoch 秒（int）。

<Note>
  `start_at` 最远只能回看到**当前时间往前 1 小时**以内（服务端 `subscribe.max_lookback`，默认 `1h`）。早于这个时间会被服务端以 `InvalidArgument` 拒绝。
</Note>

## 断线重连与游标续传

`Subscribe` 内置重连机制，无需业务层写重试：

* **自动重连**：流断开（服务端空闲收流、重启、rebalance 或报错）都会自动重连，指数退避（1s → 30s）。
* **游标续传**：重连会带上最后事件的时间游标，服务端回放断流期间的事件。
* **回放窗口**：服务端对旧游标有 1 小时回放窗口；SDK 会把游标夹到 30 分钟内，太老的游标会被丢弃、改从最新订阅（漏掉的块由上游按高度补洞）。

直接 `for ... in listen():` 消费即可，无需自己写 `try/except` 重试。

## 停止订阅

`close()` 可以从另一个线程叫停正在阻塞的 `listen()`：

```python theme={null}
sub = Subscribe(tables=[t])

# 在主线程消费
for table_id, block in sub.listen():
    ...

# 别的线程想停掉订阅
sub.close()
```

<Info>
  多表订阅若需要按高度对齐（保证所有依赖表在目标高度都已就绪），请用 `Aligned`，见[多表区块高度对齐订阅](/zh/guides/multi-table-alignment)。
</Info>

## 相关阅读

* [写入与事件订阅](/zh/concepts/write-subscribe)
* [多表区块高度对齐订阅](/zh/guides/multi-table-alignment)
* [配合 BlockX 高并发计算](/zh/guides/blockx)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.