NoSQL 与搜索 / 系统课时
批量写入服务
批量写入服务
批量写入的难点不在于一次发送很多文档,而在于控制批次、识别部分失败,并让重试不会制造重复数据。本课将实现一个可运行的 Java 服务,把分批、失败分类、重试上限和幂等边界集中在同一条流程中。
学习目标
- 按固定批次拆分写入任务,避免单次请求过大
- 区分可重试与不可重试失败,并收敛最终结果
- 使用稳定文档 ID 设计幂等重试边界
批量写入的处理链路
一次 Bulk 请求可能整体返回成功,但其中部分文档仍然失败。因此服务不能只检查 HTTP 状态,而要逐项读取结果,并把失败分成两类:限流、节点暂不可用等短暂问题可以重试;映射冲突、字段格式错误等确定性问题应立即记录,继续重试只会浪费资源。

批次大小没有固定答案,应同时观察文档平均体积、节点吞吐、写入延迟和 429 比例。与其只按条数控制,更稳妥的做法是同时限制“每批条数”和“序列化后字节数”;本课示例先用条数展示核心流程。
实现可重试的批量服务
下面的示例通过网关接口隔离 Elasticsearch 客户端。模拟网关让 p-2 首次返回可重试失败,第二次成功;p-3 返回不可重试失败,用于验证部分失败处理。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class BulkWriteDemo {
record WriteCommand(String id, String json) {}
record ItemResult(String id, boolean success, boolean retryable, String message) {}
record WriteReport(int successCount, Map<String, String> failures) {}
interface BulkGateway {
List<ItemResult> write(List<WriteCommand> commands);
}
static final class BulkWriteService {
private final BulkGateway gateway;
private final int batchSize;
private final int maxAttempts;
BulkWriteService(BulkGateway gateway, int batchSize, int maxAttempts) {
this.gateway = gateway;
this.batchSize = batchSize;
this.maxAttempts = maxAttempts;
}
WriteReport writeAll(List<WriteCommand> commands) {
Set<String> succeeded = new HashSet<>();
Map<String, String> failures = new LinkedHashMap<>();
for (int start = 0; start < commands.size(); start += batchSize) {
int end = Math.min(start + batchSize, commands.size());
List<WriteCommand> pending = new ArrayList<>(commands.subList(start, end));
for (int attempt = 1; attempt <= maxAttempts && !pending.isEmpty(); attempt++) {
List<ItemResult> results = gateway.write(pending);
Map<String, WriteCommand> byId = new HashMap<>();
pending.forEach(command -> byId.put(command.id(), command));
List<WriteCommand> retry = new ArrayList<>();
for (ItemResult result : results) {
if (result.success()) {
succeeded.add(result.id());
} else if (result.retryable() && attempt < maxAttempts) {
retry.add(byId.get(result.id()));
} else {
failures.put(result.id(), result.message());
}
}
pending = retry;
}
}
return new WriteReport(succeeded.size(), failures);
}
}
static final class FakeBulkGateway implements BulkGateway {
private final Map<String, Integer> attempts = new HashMap<>();
@Override
public List<ItemResult> write(List<WriteCommand> commands) {
List<ItemResult> results = new ArrayList<>();
for (WriteCommand command : commands) {
int attempt = attempts.merge(command.id(), 1, Integer::sum);
if (command.id().equals("p-2") && attempt == 1) {
results.add(new ItemResult(command.id(), false, true, "temporarily rejected"));
} else if (command.id().equals("p-3")) {
results.add(new ItemResult(command.id(), false, false, "mapping conflict"));
} else {
results.add(new ItemResult(command.id(), true, false, "ok"));
}
}
return results;
}
}
public static void main(String[] args) {
List<WriteCommand> commands = List.of(
new WriteCommand("p-1", "{\"name\":\"Keyboard\"}"),
new WriteCommand("p-2", "{\"name\":\"Mouse\"}"),
new WriteCommand("p-3", "{\"name\":42}")
);
BulkWriteService service = new BulkWriteService(new FakeBulkGateway(), 2, 3);
WriteReport report = service.writeAll(commands);
System.out.println("success=" + report.successCount());
System.out.println("failures=" + report.failures());
}
}预期输出:
success=2
failures={p-3=mapping conflict}生产适配器应把每个 ItemResult 对应到 Bulk 响应中的单项状态。重试前只保留可重试项,不要重新提交整个批次,否则已成功文档会被重复处理。
幂等与重试边界
最基础的幂等手段是为同一业务对象始终使用相同 _id。普通覆盖写或确定性 upsert 在重试后仍得到同一最终状态;自增脚本、追加数组或“每次调用都累加”的更新则不是天然幂等,必须增加业务版本号、请求号或外部去重记录。
重试还应采用退避策略,并对并发重试数量设上限。遇到持续 429 时,立即高频重发会进一步加重节点压力;常见做法是指数退避并加入随机抖动,同时把达到上限的项目写入失败队列或补偿表。
验收与运行指标
服务验收不能只看“调用完成”,还要核对输入数是否等于成功数、不可重试失败数和耗尽重试失败数之和。生产环境至少记录批次数、单批耗时、成功条数、失败类型、重试次数与最终失败 ID,便于判断是数据质量问题还是集群容量问题。
Tips:Bulk 请求的成功响应不等于每个文档都成功。只有逐项检查结果并保存失败原因,批量写入才具备可恢复性。
本课总结
- 批量写入应按批次执行,并逐项处理部分失败
- 只有短暂性错误进入有限重试,确定性错误应立即收敛
- 稳定文档 ID、确定性更新和可观测失败记录共同构成幂等保障
下一课预告
下一课将设计搜索服务接口,把业务请求、搜索结果与 Elasticsearch 查询结构分离,避免底层客户端类型扩散到业务模块。