Skip to content

Point-in-time recovery: the change journal

Status: implemented in phase P6 (src/journal/). This document is the contract for the on-disk format and the behaviour; the operator's view is in docs/guides/point-in-time-recovery.md.

A backup captures the database at one moment. The journal records every change after that moment, so a restore can stop at any second: just before the bad deploy, the accidental deleteMany, or the ransomware.

It reuses the converge machinery (docs/specs/CONSISTENCY.md): the same change stream (allChangesForCluster, showExpandedEvents, raw events, split events reassembled, transient errors resumed; src/engine/converge-stream.ts), the same enrichment of events replay could not express, and the same replay rules, index changes included. Capture works the same way; it just never stops.

TermMeaning
base backupan ordinary complete backup whose manifest records a cluster time: consistency.to for converge, consistency.from for snapshot. Backups with consistency none cannot be a base, and neither can incremental backups (they hold changes, not data; a time an incremental chain covers is restored through the chain, see FORMAT.md).
journala chained sequence of segments of change events, with recorded gaps
segmentone stored object holding every journaled event with a cluster time in (from, to]
recovery pointthe newest cluster time up to which the journal is complete (state.json)
RPOhow far behind "now" the recovery point is; normally under one segment interval

Ranges are half-open on the left: a segment holds the events strictly after from, up to and including to, and the next segment starts at to. A restore "to T" replays the events with cluster time <= T that are after the base backup's time.

journal/
segments/2026-11-14/031500_1763090100-0000000003.bson.zst.age
└ UTC day of `from` └ time of `from` └ `from` as t-i, zero-padded to 10 digits
state.json the commit point (see below)
gaps/1763090100-0000000003.json a recorded gap, keyed by where it starts; never pruned
locks/journal/<generation>.json the writer's lease (the scheduler's storage lock)
  • Segment keys hold only the segment's start: segments are streamed to storage while they are written, so their end is not known when the upload begins. Zero padding makes key order equal time order. The extensions (.bson, .zst/.gz, .age) say how the segment is stored, so every segment is self-describing.
  • Encryption and compression follow the configured backup settings. Segments are encrypted directly to the configured recipients and/or KMS keys (one KMS call per segment; no per-journal key file), so each segment is its own age file and never depends on another. The KMS call of each segment takes the writer's (or reader's) abort signal, so a stopping writer never waits on a slow KMS. Passphrases are refused (MS_CONFIG_INVALID): age runs scrypt for every file, and a journal writes a file every few minutes forever.

Concatenated BSON documents, compressed and encrypted as a whole:

{ op: "segment", formatVersion: 1, from: Timestamp, previous: <hex sha256> | null }
<change event> … raw, exactly as the server sent them (see below)
{ op: "segment-end", to: Timestamp, events: Int64 }
  • previous is the SHA-256 of the previous segment's stored bytes (after compression and encryption), so the chain can be checked without a key for the hashing part. It is null for the first segment ever written. Across a gap it still names the last segment before the gap.
  • Change events are stored verbatim, except the two cases converge also handles (CONSISTENCY.md and FORMAT.md): updates to field names containing . or starting with $ get the document as of the event in fullDocument (snapshot read at the event's cluster time), and renames into a journaled namespace from a namespace the journal does not record (an excluded collection, or an $out/$merge scratch collection tmp.*, which the journal skips) are followed by synthesized drop + create + insert events (marked synthesized: true) that record the destination as of the rename.
{
"formatVersion": 1,
"recoveryPoint": { "t": 1763090400, "i": 3 },
"lastSegment": { "key": "journal/segments/…", "from": {…}, "to": {…}, "size": 1234,
"sha256": "…", "events": 812 },
"totals": { "segments": 1500, "events": 9000000, "bytes": 812000000 },
"updatedAt": "2026-11-14T03:20:01.123Z",
"writer": { "host": "journal-7d9f", "pid": 1 }
}

A segment belongs to the journal once state.json names it or a later segment. Segments with a later start are interrupted uploads: readers ignore them and the next writer deletes them (it would overwrite the same key anyway, since it starts at the recovery point). totals never decrease (pruning does not touch them); planning uses them to estimate the number of events per stored byte.

{ "formatVersion": 1, "from": { "t": …, "i": … }, "to": { "t": …, "i": … },
"detectedAt": "…", "reason": "<server message>", "action": "backup" | "fail" }

Changes in (from, to] are lost. from is the recovery point when the gap was found; to is where the journal starts again.

Without opening a segment: committed segments sorted by start; each ends where the next starts, or where a gap that starts in between starts; the newest ends at the recovery point. Consecutive segments form covered ranges. Names cannot prove that nothing is missing or altered; the chain does (see "Reading").

The writer: mongoshield journal start / startJournal()

Section titled “The writer: mongoshield journal start / startJournal()”

A long-running process. It runs as a library call (startJournal({ client, storage, … }) returns a handle with stop(), status() and done) or as mongoshield journal start (a container, a systemd service, a Kubernetes Deployment with one replica).

  1. Lease. Take the storage lease locks/journal/ (the scheduler's storage lock, src/schedule/lock-storage.ts, default 60 s, renewed every third of it). A second writer fails with MS_STORAGE_PRECONDITION_FAILED, or waits with waitForLease. A writer that loses its lease stops at once.
  2. Resume. With a state.json: after its recovery point, skipping recorded gaps that start there. Without one (a new journal, and no segment in storage): at the newest base backup's cluster time, or at "now" with a warning that recovery is only possible from the next base backup. A journal with segments but no state.json is refused (MS_CONFIG_INVALID) rather than guessed at. The change stream is opened with startAtOperationTime = the cluster time right after the resume point, which returns exactly the later events because segments never end inside a cluster time (step 3). Its cursor carries the comment mongoshield journal, and the server filters by database like the converge capture does (only the databases the include patterns name, when every pattern names one literally).
  3. Segments. Events stream into the current segment (getMore → compress → encrypt → SHA-256 → storage.put; memory stays flat). A segment closes once it is segmentSeconds old (default 300) or holds segmentBytes of events (default 64 MiB), and on stop(). mongoshield journal start takes both, and onGap (step 5), from the config file's journal section ({ segmentSeconds, segmentBytes, onGap }); its flags --segment-seconds, --segment-size and --on-gap override them. It may only end at a cluster time T with every event up to T in it and none after:
    • an event with a later cluster time than the previous one arrives → T is the previous one (the events of a transaction share a cluster time and are never split);
    • an empty batch reports the stream's position P (postBatchResumeToken) → T is P. Closing means: write the trailer, finish the upload, then rewrite state.json.
  4. Heartbeat segments. An idle database still produces a segment every interval: header and trailer only, ending at the stream's position, so the recovery point keeps moving (the oplog advances at least with the server's periodic no-op writes, every 10 s).
  5. Gaps. When the oplog no longer reaches the resume point (ChangeStreamHistoryLost, ChangeStreamFatalError, CappedPositionLost): write a gap record, alert (notify targets get a failure report; the heartbeat gets /fail), and then
    • onGap: "backup" (the default when a takeBaseBackup callback is given): keep journaling from "now" and take a new base backup in the background;
    • onGap: "fail" (the default otherwise): stop with MS_CHANGE_HISTORY_LOST. A restarted writer continues after the recorded gap. A brand-new journal that cannot start at an old base backup simply starts now (no gap).
  6. Transient failures. A dropped connection or a killed session on the change stream is first handled by the stream itself: it reopens after the last batch's resume token (up to 5 attempts over about 3 s, see CONSISTENCY.md, "Interruptions"), and the segment being written goes on as if nothing happened. Only when that fails, and on storage errors, the writer abandons the open segment (its upload is discarded) and restarts from the last commit after 1 s, 2 s, 4 s … up to 60 s. Missing privileges, invalid settings, forbidden storage, a lost lease and a change event over the server's size limit (MS_UNSUPPORTED_TOPOLOGY, CONSISTENCY.md, "Large events": retrying would fail on the same event) stop the writer.
  7. Metrics. status(): recovery point, RPO, segments/events/bytes written, events per second, last segment latency (closing → committed), gaps, last transient error. Every committed segment pings the configured heartbeat URL and calls onSegment.

Reading: readJournalSegments(storage, { from, to, decryption })

Section titled “Reading: readJournalSegments(storage, { from, to, decryption })”

Yields the events in (from, to] in order and checks, for every segment involved:

  • the header names its own start (as in its key) and the SHA-256 of the previous segment's stored bytes (for the first segment of the range, the previous segment is downloaded and hashed);
  • events are in cluster-time order, inside the segment's range;
  • the trailer names the segment's end as derived from the names (the next segment's start, a gap's start, or the recovery point) and its event count;
  • the last segment's digest matches the next segment's previous, or, for the newest segment, state.json's lastSegment.sha256.

A missing, reordered, truncated or altered segment fails with MS_INTEGRITY_FAILED; a range the journal does not cover (a gap, or past the recovery point) fails with MS_CHANGE_HISTORY_LOST. Segments encrypted to KMS keys open through the KMS when no given identity matches. verifyJournal(storage) reads every covered range.

at is a Date or a cluster time. A Date is rounded down to its second, and that second's writes are not replayed (cluster time { t: <second>, i: 0 }): when someone names the second the bad deleteMany ran, replaying that second might replay it. Pass a cluster time for exact control.

  1. planPointInTimeRestore(storage, at, { include, exclude, clusterId, instanceId }): the newest complete base backup whose cluster time is at or before at and that suits the restore (src/journal/base-suitability.ts):

    • it covers every namespace the restore selects: each is in the base, or the base's recorded selection would have backed it up (a collection created after it). The namespaces checked are those of every complete backup in the location plus the include patterns without *;
    • it has no query filter on a selected namespace;
    • with clusterId (and instanceId, for two replica sets sharing a set name), it comes from that deployment. Without it, each base is judged against its own deployment's backups only, and the newest suitable one at or before at decides; when suitable bases of other deployments lie inside the journal range the restore uses, the plan's warnings say so (the journal does not record its deployment). One plan never mixes deployments. restore({ at }) passes sourceIdentity, else the configured source's identity (never the target's); mongoshield restore --at takes --source-cluster <clusterId>[/<instanceId>], else the configured source's.

    Unsuitable newer bases are passed over (listed in the error and in details.skippedBases when nothing suitable is left). Manifests written before selections were recorded are accepted unchecked. Then: a covered range from the base's time through at, and the segments holding (base time, at] (with their stored size and an estimate of the number of events). Only names, manifests and small records are read. Otherwise MS_CHANGE_HISTORY_LOST, listing the recoverable ranges (also in details.recoverableRanges): within each covered range, from its oldest base backup to its end, plus every base backup on its own.

  2. Pre-flight, BEFORE the base restore and in dry runs too (preflightJournal in src/journal/replay.ts): reads the whole range (base time, at] once (chain, decryption, parsing); with baseSelection (the plan's), refuses journaled namespaces the restore selects that the base neither holds nor would have backed up (MS_CHANGE_HISTORY_LOST); conflict-checks the targets of collections created after the base backup with mode (MS_RESTORE_CONFLICT). A refusal here leaves the target untouched; a refusal after the base restore would leave it at the base backup's time.

  3. Restore the base backup as usual (including its own converge replay and index builds).

  4. replayJournal({ client, storage, preflight, from: base time, to: at, baseNamespaces, baseSelection, include, exclude, rename, mode, decryption, … }): reuses the pre-flight (without one it runs its own before writing anything); maps namespaces with the restore's rules (src/engine/converge-targets.ts; collections created after the base backup are conflict-checked with mode again, and dropped first in mode drop), then replays with the converge rules (src/engine/converge-replay.ts). Index changes after the base backup (the indexes of collections created after it included) are applied once the documents are in, with the converge rules (src/engine/converge-indexes.ts; the base restore has built the base backup's indexes already); skipIndexes leaves them out.

  5. Report the exact cluster time restored to (restoredTo), the number of events and the indexes created and dropped (indexesCreated, indexesDropped).

When the journal does not reach at, or the pre-flight finds the base does not cover what it changes (MS_CHANGE_HISTORY_LOST either way), restore({ backup: "latest", at }) looks for an intact incremental chain that covers at and restores it up to at instead; the error lists the chains' ranges next to the journal's when none does.

mongoshield journal status shows the recovery point, the RPO, the covered ranges and any gaps (--json for scripts, --max-rpo 10m exits 1 when the journal is further behind). mongoshield restore --at (with --dry-run showing the plan and running the pre-flight) wires steps 1 to 4.

Journal segments that end at or before the oldest kept base backup are useless, because nothing can be replayed onto them. pruneJournal(storage, { olderThan }) deletes them; run it after pruning backups with the oldest remaining base backup's cluster time (listBaseBackups). The newest segment and gap records are never pruned.

  • The same as converge (CONSISTENCY.md): DDL other than create, drop, rename, createIndexes and dropIndexes is not replayed; time series collections are not journaled (change streams do not report their writes); a change event over the server's size limit stops the writer.
  • Base backups must include every namespace the journal records (same include/exclude).
  • The two enrichments (dotted field names, rename destinations) are snapshot reads at the event's cluster time: a writer catching up from further behind than the server's snapshot window (minSnapshotHistoryWindowInSeconds, 300 s) cannot record them exactly and logs an error for each.
  • Lost history is detected by the server. A replica set whose oplog never rolled over accepts any start time, because its first entry marks the beginning of history.