高吞吐通用攒批管道(Batch Ingest)
面向埋点上报、审计日志、行情流水与 IoT 遥测等高频写入场景的协议无关攒批缓冲引擎。应用在同一个进程内可注册多条具名强类型独立管道,按「条数上限 / 字节上限 / 刷新周期」三触发条件聚合成批后调用业务 BatchSink 落盘,内置双水位背压、指数退避重试、二分拆条毒丸隔离、死信回调、停机零丢数排空,以及可选的 Redis Streams 持久化与多实例崩溃接管后端。
flowchart LR
req["HTTP / Procedure / Task 调用 ctx.batch_ingester::<T>(name)"] --> buf["有界缓冲区(Memory 或 Redis Streams)"]
buf -->|"条数 / 字节 / 定时三触发"| flush["后台刷批引擎(指数退避重试)"]
flush --> sink["BatchSink::flush(ctx, batch)"]
flush -->|"Poisoned 毒丸错误"| bisect["二分拆条隔离坏记录"]
bisect --> dlq["BatchDeadLetterSink(死信落盘 / 告警)"]快速接入#
在 Cargo.toml 开启主包 kxed 的 batch-ingest 特性(多实例持久化缓冲与崩溃接管开启 batch-ingest-redis 或直接使用 cluster-backends):
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["batch-ingest", "batch-ingest-redis"] }实现 BatchSink<T> 并在 BatchIngestPlugin 上注册具名管道,请求处理器经 ctx.batch_ingester::<T>("events")? 提交记录:
use async_trait::async_trait;
use kxed::plugins::batch_ingest::{
BatchFlushError, BatchIngestPlugin, BatchPipelineOptions, BatchPipelineSpec, BatchSink,
};
use kxed::prelude::*;
use std::time::Duration;
#[derive(Clone, Serialize, Deserialize)]
pub struct AuditEvent {
pub actor: String,
pub action: String,
}
struct AuditSink;
#[async_trait]
impl BatchSink<AuditEvent> for AuditSink {
async fn flush(&self, ctx: &AppCtx, batch: Vec<AuditEvent>) -> Result<(), BatchFlushError> {
// 使用单条批量 INSERT 将 batch 写入数据库或 ClickHouse...
let _ = (ctx, batch);
Ok(())
}
fn estimate_bytes(&self, item: &AuditEvent) -> usize {
item.actor.len() + item.action.len() + 32
}
}
#[mutation(name = "audit.record", post = "/api/audit")]
pub async fn record_audit(ctx: &AppCtx, input: AuditEvent) -> Result<(), AppErr> {
ctx.batch_ingester::<AuditEvent>("audit")?
.enqueue(input)
.await?;
Ok(())
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
let spec = BatchPipelineSpec::new("audit", AuditSink)
.with_json_codec()
.with_options(
BatchPipelineOptions::new()
.with_max_batch_items(200)
.with_flush_interval(Duration::from_millis(300)),
);
App::new()
.plugin(BatchIngestPlugin::new().with_pipeline_spec(spec))
.run()
.await
}核心用法#
注册管道与单管道覆写#
管道名称须符合 1..=64 位 [a-z0-9_-] 且以小写字母或数字开头。BatchIngestPlugin 提供三种注册入口:
with_pipeline(name, sink):注册内存攒批管道,记录类型T无需实现Serialize。with_durable_pipeline(name, sink):自带JsonRecordCodec<T>,可直接按配置在memory与redis后端间无代码切换。with_pipeline_spec(BatchPipelineSpec):完整配置单管道死信接收器.with_dead_letter(...)、自定义编解码器.with_codec(...)及单管道覆写参数BatchPipelineOptions(未覆写字段继承[batch_ingest]全局配置)。
记录类型含 String、Vec 或 serde_json::Value 等堆分配字段时,建议在 BatchSink::estimate_bytes 中返回接近实际占用的字节估算值,使 max_batch_bytes 与 max_buffered_bytes 水位精准生效。
入队、背压与手动冲刷#
ctx.batch_ingester::<T>(name)? 返回的 BatchIngester<T> 自动绑定当前请求的 AppCtx::deadline() 与取消信号:
| 方法 | 行为说明 |
|---|---|
enqueue(item) / enqueue_many(iter) | 提交单条或原子提交多条记录;BackpressurePolicy::Reject 满载立返 503 batch_ingest_busy,Wait 模式等待释放且受请求剩余期限与 wait_timeout 约束 |
enqueue_for(item, dur) / enqueue_by(item, deadline) | 为本次等待附加更严格的超时或绝对截止时刻 |
try_enqueue(item) / try_enqueue_many(iter) | 非阻塞入队,仅适用于 memory 后端(redis 后端须使用异步 enqueue) |
flush() | 立即触发一次刷批并等待此前已入队的记录完成落盘或转入死信 |
snapshot() / is_draining() | 读取当前管道实时水位、累计入队/刷批/死信计数及停机排空状态 |
单次提交的条数或字节数超过管道缓冲总上限(max_buffered_items / max_buffered_bytes)时直接返回 413 batch_ingest_too_large,不会阻塞等待。
刷批错误分类、毒丸二分隔离与死信#
BatchSink::flush 通过返回 BatchFlushError 的三种变体精确控制后续处理,绝不静默丢弃数据:
BatchFlushError 变体 | 引擎处置策略 |
|---|---|
Retryable { message, retry_after } | 暂时性故障(锁等待、连接抖动、503),按 initial_backoff 至 max_backoff 指数退避重试至 max_retries;若指定 retry_after 优先尊重该延迟;耗尽后整批送入 BatchDeadLetterSink(DeadLetterKind::RetriesExhausted) |
Poisoned { message } | 开启 isolate_poisoned = true(默认)时自动二分拆批重试,放行所有正常记录,将定位到的坏记录交 BatchDeadLetterSink(DeadLetterKind::Poisoned) |
Fatal { message } | 永久错误(权限失效、表缺失),立即停止重试并整批交 BatchDeadLetterSink(DeadLetterKind::Fatal) |
停机零丢数排空与多实例 Redis Streams#
- 优雅停机排空:进程收到停机信号进入
begin_drain时,所有管道立即拒绝新入队(返回 503batch_ingest_draining)并触发冲刷;drain阶段在min(drain_timeout, ctx.remaining())预算内等待全部已入队内存数据落盘或转入死信,确保滚动发布零丢数。 - 多实例集群部署:集群拓扑下若仍有管道使用
memory后端,启动阶段会打印醒目告警(提示kill -9强杀会丢失进程内未落盘数据)。生产多实例需强持久与崩溃接管时,开启batch-ingest-redis(或cluster-backends),注册RedisPlugin并设置batch_ingest.backend = "redis":写入先落 Redis Stream(键名<redis_key_prefix><pipeline>,受MAXLEN ~ redis_stream_max_len保护),消费组按XREADGROUP攒批落盘后XACK,崩溃节点遗留的空闲消息超过redis_claim_idle_timeout后由存活实例通过XAUTOCLAIM自动接管。
配置#
| 键 | 缺省 | 范围与含义 |
|---|---|---|
batch_ingest.backend | memory | 缓冲后端:memory(进程内有界缓冲)或 redis(Redis Streams 持久化缓冲) |
batch_ingest.max_batch_items | 500 | 单批最大记录条数,范围 1..=100000 |
batch_ingest.max_batch_bytes | 1048576(1 MiB) | 单批最大估算字节数,范围 64..=256 MiB |
batch_ingest.flush_interval | 500ms | 定时刷批最大等待间隔,范围 1ms..=5m |
batch_ingest.max_buffered_items | 10000 | 管道缓冲区最大记录条数,不小于 max_batch_items,上限 10000000 |
batch_ingest.max_buffered_bytes | 33554432(32 MiB) | 管道缓冲区最大估算字节数,不小于 max_batch_bytes,上限 2 GiB |
batch_ingest.backpressure | reject | 缓冲满载策略:reject(立返 503)或 wait(在期限内等待释放) |
batch_ingest.wait_timeout | 5s | wait 策略单次入队默认等待上限,范围 1ms..=5m |
batch_ingest.max_retries | 3 | 可重试刷批失败的最大重试次数,范围 0..=20 |
batch_ingest.initial_backoff | 100ms | 指数退避初始延迟,上限 1m |
batch_ingest.max_backoff | 5s | 指数退避最大延迟,范围 initial_backoff..=10m |
batch_ingest.isolate_poisoned | true | 遇 BatchFlushError::Poisoned 时是否启用二分拆条隔离坏记录 |
batch_ingest.dead_letter_policy | log_and_drop | 无死信接收器时策略:log_and_drop(默认,记错确认)或 require_sink(强制要求死信接收器且拒绝无死信 XACK) |
batch_ingest.drain_timeout | 15s | 停机排空单管道最大等待时长,范围 100ms..=10m |
batch_ingest.redis_key_prefix | kxed:batch_ingest: | Redis Stream 键名前缀,1..=128 字节无空白 |
batch_ingest.redis_stream_max_len | 100000 | 单管道 Redis Stream 近似最大保留条数,范围 1..=10000000 |
batch_ingest.redis_consumer_group | kxed-batch-ingest | Redis Streams 消费组名称,1..=64 字节无空白 |
batch_ingest.redis_claim_idle_timeout | 30s | 崩溃节点挂起消息被 XAUTOCLAIM 接管前的空闲阈值,范围 100ms..=1h |
batch_ingest.redis_poll_interval | 100ms | Redis Streams 后台拉取轮询间隔,范围 10ms..=30s |
错误码与 Prometheus 指标#
BatchIngestError 经 batch_ingest_error_of(或 ?)映射为带 CallFailure 分级的 AppErr:
BatchIngestError 变体 | HTTP 状态码 | 错误码 | 说明 |
|---|---|---|---|
Overloaded | 503 | batch_ingest_busy | 缓冲区已满且策略为 reject(NotExecuted,可退避重试) |
Draining | 503 | batch_ingest_draining | 管道正处于停机排空阶段(NotExecuted) |
DeadlineExceeded | 503 | batch_ingest_timeout | wait 模式下等待缓冲释放超时或取消(NotExecuted) |
BackendUnavailable | 503 | batch_ingest_unavailable | Redis Stream 后端不可达或不支持同步非阻塞入队(NotExecuted) |
Closed | 503 | batch_ingest_closed | 后台刷批协程已退出(NotExecuted) |
PayloadTooLarge | 413 | batch_ingest_too_large | 单次提交体超过缓冲区最大容量上限(Settled) |
NotRegistered / PipelineNotFound / PipelineTypeMismatch / Serialization | 500 | state_not_registered / batch_ingest_not_found / batch_ingest_mismatch / encode_failed | 装配缺失、管道名或泛型类型不匹配、编解码失败 |
| 指标 | 类型与标签 | 含义 |
|---|---|---|
kxed_batch_ingest_enqueue_total | Counter(name, outcome) | 入队请求计数(accepted 或各类拒收结局) |
kxed_batch_ingest_flush_total | Counter(name, outcome) | 刷批执行结局计数(ok / 重试 / 死信等) |
kxed_batch_ingest_flush_duration_seconds | Histogram(name) | 单次刷批落盘耗时(秒) |
kxed_batch_ingest_dead_letter_total | Counter(name) | 进入死信回调的记录总数 |
kxed_batch_ingest_buffered_items | Gauge(name) | 当前缓冲区待落盘的记录条数 |
kxed_batch_ingest_buffered_bytes | Gauge(name) | 当前缓冲区待落盘的估算字节数 |