用 ETag 与 If-Match 实现 REST 更新的乐观并发控制
资源更新接口最常见的事故是后写覆盖先写:客户端 A 和 B 同时读到 version 1,A 先 PUT 成功,B 随后用旧数据 PUT,把 A 的修改覆盖掉。用 ETag 与 If-Match 可以把“读—改—写”变成带条件的更新:GET 在响应头返回当前版本 ETag,PUT 必须通过 If-Match 声明自己基于哪个版本修改;服务器只在版本一致时更新,否则返回 412 Precondition Failed,并带回当前 ETag,客户端重新读取后再决定是否重试。下面给出一份可直接运行的 Express 最小实现。
协议约定
- ETag 使用强验证器格式,例如
"v1";不要用W/"v1"弱标签,因为 If-Match 使用强比较。 GET /items/:id成功时设置 ETag。PUT /items/:id必须携带 If-Match;缺失返回 428 Precondition Required。团队也可以约定为 400,但应在 API 文档中固定。- 版本不匹配返回 412,并在响应头与响应体给出当前 ETag。
- 更新成功返回 200,版本递增并返回新 ETag。
If-Match: *表示只要资源存在就允许更新,它会绕过版本比较,业务要慎用。- If-Match 可以是逗号分隔的多个 ETag,强比较任一匹配即可。
最小可运行示例
保存为 server.js:
const express = require('express');
const app = express();
app.use(express.json());
const etagOf = (version) => `"v${version}"`;
const store = new Map([
['1', { id: '1', name: 'demo', version: 1 }],
]);
function readIfMatch(req) {
const raw = req.get('If-Match');
if (!raw) return null;
return raw.split(',').map((s) => s.trim()).filter(Boolean);
}
function ifMatchAllows(ifMatch, currentETag) {
if (ifMatch.length === 1 && ifMatch[0] === '*') return true;
return ifMatch.includes(currentETag);
}
function requireIfMatch(req, res, next) {
const current = store.get(req.params.id);
if (!current) {
return res.status(404).json({ error: 'not_found' });
}
const currentETag = etagOf(current.version);
const ifMatch = readIfMatch(req);
if (!ifMatch) {
res.set('ETag', currentETag);
return res.status(428).json({ error: 'if_match_required', currentETag });
}
if (!ifMatchAllows(ifMatch, currentETag)) {
res.set('ETag', currentETag);
return res.status(412).json({ error: 'precondition_failed', currentETag });
}
req.current = current;
req.currentETag = currentETag;
next();
}
app.get('/items/:id', (req, res) => {
const item = store.get(req.params.id);
if (!item) return res.status(404).json({ error: 'not_found' });
res.set('ETag', etagOf(item.version));
res.json(item);
});
app.put('/items/:id', requireIfMatch, (req, res) => {
const id = req.params.id;
const { name } = req.body || {};
if (typeof name !== 'string' || name.trim() === '') {
res.set('ETag', req.currentETag);
return res.status(400).json({ error: 'invalid_body' });
}
const current = store.get(id);
if (!current) return res.status(404).json({ error: 'not_found' });
if (current.version !== req.current.version) {
const latestETag = etagOf(current.version);
res.set('ETag', latestETag);
return res.status(412).json({ error: 'precondition_failed', currentETag: latestETag });
}
const next = { ...current, name, version: current.version + 1 };
store.set(id, next);
res.set('ETag', etagOf(next.version));
res.json(next);
});
app.listen(3000, () => {
console.log('listening on http://localhost:3000');
});
运行与 curl 验证
先安装依赖并启动:
npm init -y
npm install express
node server.js
读取资源,确认响应头中的 ETag:
curl -i http://localhost:3000/items/1
预期返回 200,响应头含 ETag: "v1",响应体中的 version 为 1。
携带当前 ETag 更新:
curl -i -X PUT http://localhost:3000/items/1 -H 'Content-Type: application/json' -H 'If-Match: "v1"' -d '{"name":"first-update"}'
预期返回 200,响应头中的 ETag 变为 "v2"。
再用旧 ETag 重放一次,模拟后写覆盖:
curl -i -X PUT http://localhost:3000/items/1 -H 'Content-Type: application/json' -H 'If-Match: "v1"' -d '{"name":"stale-update"}'
预期返回 412,响应头带 ETag: "v2",响应体给出 currentETag 为 "v2"。客户端应重新 GET,基于新版本修改后再 PUT。
省略 If-Match 时:
curl -i -X PUT http://localhost:3000/items/1 -H 'Content-Type: application/json' -d '{"name":"no-if-match"}'
预期返回 428,并带当前 ETag。若团队约定缺失前置条件用 400,也应在文档中统一。
关键点:预检不等于原子更新
中间件 requireIfMatch 负责快速失败和返回 412/428,但真正防止覆盖的是存储层的条件更新。示例在 PUT 处理函数中再次读取版本并比较,然后在同步函数内写入;单进程中没有 await 插入,因此检查与写入是原子的。
生产环境不能依赖进程内原子性。多实例部署时,应把比较和更新放进同一条 SQL 条件更新、事务,或 Redis 的原子脚本。例如:
UPDATE items
SET name = ?, version = version + 1
WHERE id = ? AND version = ?;
受影响行数为 0 时,读取当前版本并返回 412;受影响行数为 1 时,再读取新版本设置新 ETag,或使用所用数据库支持的返回能力。具体写法以数据库文档为准。
边界与限制
- 内存 Map 重启即丢失,也不能横向扩展,仅用于演示。多实例应使用数据库版本列、事务或 Redis 原子操作。
- ETag 不是权限控制。应先做认证与授权,再处理 404/412,避免通过状态码或 ETag 泄露资源存在性。
- 代理、网关和 CORS 场景要确保 If-Match 与 ETag 透传;浏览器读取 ETag 需要
Access-Control-Expose-Headers: ETag。 - 弱 ETag 不适合 If-Match;如果用内容哈希生成 ETag,必须保证每次修改后变化且碰撞可接受。
If-Match: *会削弱并发保护;需要严格防覆盖时,应禁止或限制使用。- GET 的 If-None-Match/304 是缓存验证,和更新时的并发控制不是同一件事,不要混用。
- 请求体校验失败不应消耗版本;示例先校验 name,再做条件更新。412 响应体只返回最小信息,完整错误格式可按团队规范定义。
小结
GET 返回版本 ETag,PUT 强制 If-Match,存储层做原子条件比较;不匹配时返回 412 并回传当前 ETag。这样能把“后写覆盖先写”变成可检测、可重试的冲突,但多实例下必须由数据库或原子存储保证最终一致性。
- 点赞
- 收藏
- 关注作者
评论(0)