At 02:14 the checkout total for every EU customer drops by 19%. By 02:31
support has three refund requests and nobody knows why. The on-call engineer
has application logs, a metrics dashboard, and a database where the current
values are already wrong.
The question is not "what is the current price?". It is:
- what was the price at 02:10,
- what changed at 02:14,
- which other documents changed in the same window,
- and can we prove the rollback fixed exactly the damage?
Application logs rarely answer this. A log line says price updated, not
price was 129.00, now 104.49. Backups answer the first question only if you
restore them somewhere, and they give you one snapshot, not a timeline.
This is the problem document versioning solves. Instead of an audit table with
triggers and a CDC pipeline, a history-enabled collection records every insert,
update, and delete as an immutable revision, in the same transaction as the
current document.
Set it up before you need it
from nonodb import NonoDB db = NonoDB(base_url="http://127.0.0.1:7878", token=TOKEN) products = db.collection("products") config = db.collection("config") db.set_collection_history("products", 100) db.set_collection_history("config", 100) There is no retroactive backfill. A collection that already has documents starts
recording history at the next write after the setting is applied. That is the
uncomfortable part of incident forensics: the feature only helps for the future.
Enable it on the collections that can hurt you — prices, plans, permissions,
configuration, billing rules — before the incident.
0 disables new history writes. Retention changes are applied by a background
pruning job, not synchronously. Retention is per collection and counts
revisions per document, not days.
Step 1: get one document's timeline
The first suspicious record is a product:
revs = products.history("sku_1042", limit=50, include_docs=True) for rev in revs: print(rev["rev"], rev["op"], rev["at"], rev.get("doc", {}).get("price")) history returns newest first. Each revision carries:
-
rev— a globally monotonic revision ID, -
op—insert,update, ordelete, -
at— Unix milliseconds, -
deleted— true for a tombstone, -
doc— the full document snapshot wheninclude_docs=True.
rev is global, not per-document. A single product's revisions can be 91200,
91234, 91877 because other documents took numbers in between. That is not a
bug; it is what makes cross-document correlation possible in the next step.
One exact revision is available without listing:
before = products.get_version("sku_1042", 91233) # None if retention has already pruned it The None matters during an incident. If the change is older than the retention
window, you are back to backups. Retention 100 is enough for "what happened last
week" on a low-write collection, not for a high-volume one.
Step 2: diff the exact change
A timestamp tells you when. A diff tells you what.
def diff(before: dict, after: dict) -> list[dict]: keys = set(before) | set(after) changes = [] for key in sorted(keys): if key.startswith("_"): continue old = before.get(key, "<missing>") new = after.get(key, "<missing>") if old != new: changes.append({"field": key, "from": old, "to": new}) return changes def changes_for(coll, doc_id: str): revs = coll.history(doc_id, limit=100, include_docs=True) out = [] for newer, older in zip(revs, revs[1:]): out.append({ "rev": newer["rev"], "op": newer["op"], "at": newer["at"], "changes": diff(older.get("doc", {}), newer.get("doc", {})), }) return out Output:
rev 91877 02:14:07 update price: 12900 -> 10449 tax_rate: 0.19 -> 0.00 Now the incident has a shape: tax_rate was zeroed on a product document.
That is not a normal price edit. It looks like a configuration value leaked into
the wrong field, or a migration wrote the wrong mapping.
Step 3: correlate across documents
This is where a global revision ID earns its keep. Pull the history for every
document in the suspicious set and sort by rev:
def timeline(collections: dict, ids_by_coll: dict, limit: int = 1000): events = [] for coll_name, ids in ids_by_coll.items(): coll = collections[coll_name] for doc_id in ids: for rev in coll.history(doc_id, limit=limit, include_docs=True): events.append({ "coll": coll_name, "doc_id": doc_id, "rev": rev["rev"], "op": rev["op"], "at": rev["at"], "deleted": rev["deleted"], "doc": rev.get("doc"), }) events.sort(key=lambda event: event["rev"]) return events events = timeline( {"products": products, "config": config}, { "products": ["sku_1042", "sku_1043", "sku_1050"], "config": ["pricing"], }, ) The sorted output might show:
rev 91870 02:13:52 config/pricing update vat_mode: "inclusive" -> "exclusive" rev 91877 02:14:07 products/sku_1042 update tax_rate: 0.19 -> 0 rev 91878 02:14:07 products/sku_1043 update tax_rate: 0.19 -> 0 rev 91879 02:14:08 products/sku_1050 update tax_rate: 0.19 -> 0 That is a causal story you can put in a ticket: a config change at rev 91870,
followed 15 seconds later by a writer that applied the new mode incorrectly.
Two honest caveats:
- Global
revgives you the daemon's commit order for the revisions you fetched. It is not a collection-wide point-in-time snapshot, and unrelated writes interleave. Use the ordering to correlate, not to claim "the whole database at rev X". - History is per document. There is no
find_as_of(rev)that returns every document as it looked at a past revision. You can reconstruct individual documents withget_version, and you can reconstruct a candidate set by walking revisions, but this is not a temporal database.
Step 4: measure the blast radius
"Which other documents did the bad writer touch?" The cheapest answer is a
normal query on a field the writer maintained, then history for each candidate:
suspects = products.find( {"updated_at": {"$gte": incident_start_ms}}, projection={"_id": 1}, limit=5000, ) affected = [] for row in suspects: for change in changes_for(products, row["_id"]): if change["rev"] < incident_start_rev: continue if any(c["field"] == "tax_rate" for c in change["changes"]): affected.append({"id": row["_id"], **change}) If the app does not maintain updated_at, this is harder: you need a candidate
set from an index, an event feed, or a scan. History helps most when the write
path also records a timestamp or an actor. That is application discipline, not a
database feature.
For future incidents, enable automatic collection events on the same collection:
db.set_collection_events( "products", enabled=True, ops=["update"], fields=["price", "tax_rate"], include_before=True, include_after=True, projection={"_id": 1, "price": 1, "tax_rate": 1}, ) Events go to _events in the same transaction as the write. A consumer with a
checkpoint can forward them to a SIEM or a Slack alert. History is for
reconstruction; events are for detection.
Step 5: roll back only the damage
Do not restore the whole document from 02:10. That would also revert the
legitimate copy edit and inventory change that happened between 02:10 and 02:14.
Restore the affected fields from the last known-good revision:
def restore_fields(coll, doc_id: str, rev: int, fields: list[str], actor: str): revision = coll.get_version(doc_id, rev) if revision is None or revision["deleted"]: raise ValueError("no usable revision") old = revision["doc"] set_fields = {field: old[field] for field in fields if field in old} unset_fields = {field: "" for field in fields if field not in old} update = {} if set_fields: update["$set"] = set_fields if unset_fields: update["$unset"] = unset_fields update.setdefault("$set", {}).update({ "incident": "INC-2026-014", "restored_from_rev": rev, "restored_by": actor, }) coll.update({"_id": doc_id}, update) Every rollback is itself a new revision, so the timeline reads "bad change,
rollback", not "the mistake never happened". That is what an auditor wants to
see. restored_from_rev also makes the evidence chain explicit.
Run the restore for the affected set, then verify:
remaining = [ doc["_id"] for doc in products.find({"tax_rate": 0}, projection={"_id": 1}) if doc["_id"] in {item["id"] for item in affected} ] assert not remaining The verification is a normal query; you do not need a special audit tool.
Step 6: export the evidence
An incident review needs a file, not a dashboard session. A single JSON document
with the timeline and diffs is enough:
import json from datetime import datetime, timezone report = { "incident": "INC-2026-014", "generated_at": datetime.now(timezone.utc).isoformat(), "window": {"from_rev": 91860, "to_rev": 91920}, "timeline": events, "affected": affected, } with open("inc-2026-014.json", "w") as fh: json.dump(report, fh, indent=2, default=str) Because snapshots are plain JSON, the report is readable without the database.
That also means it may contain sensitive fields. Project or redact before
attaching it outside the on-call channel.
The costs and the honest limits
Document versioning is not free:
- Write amplification. The docs describe roughly one extra document copy per write for a history-enabled collection. A 2 KB document updated 1,000 times a day with retention 100 costs real disk and real fsync work.
- Retention is a count, not a time policy. If you need "seven years", a per-document revision cap is the wrong tool. Keep immutable snapshots in a separate collection and ship them to compliance storage.
- No actor identity. Revisions record operation and time, not "Alice". Put
updated_byon the document or emit an event with metadata. - No retroactive history. Enabling it today does not explain yesterday.
- Not tamper-evident. An admin can change data. History protects against application mistakes and supports rollback; it is not a WORM archive.
- Pruning is asynchronous. The maintenance worker removes excess revisions in bounded batches. A very recent revision is normally safe; an old one near the retention boundary may disappear between your query and your restore.
For the 2 a.m. question — what changed, in what order, and how do we undo just
that — a collection setting and two read operations beat a CDC pipeline you have
to build and operate. The next article applies the same revisions to a different
problem: proving what a customer actually signed.