The deploy was fine. The config change was not.
Someone changed checkout.max_items from 50 to "50", or flipped
payments.capture_mode to "manual", or published a full config document with
one stale section. The application starts, reads the config, and starts failing
requests. The fastest fix is not a rollback of the application — the code did
not change. The fastest fix is to restore the previous configuration.
If the config is a row in a database, "restore the previous configuration"
should be one operation, not a ticket to the platform team. This post builds
that operation with a versioned config document, a compare-and-swap publish,
and a rollback that is itself audited.
The config document
Keep the active config in one document per key. Small configs are easier to
reason about when the active state is a single atomic value.
{ "_id": "checkout", "version": 12, "values": { "max_items": 50, "capture_mode": "automatic", "countries": ["PL", "DE", "CZ"], "free_shipping_threshold": 19900 }, "updated_by": "alice@example.com", "updated_at": {"$date": "2026-01-14T10:02:11Z"} } Two fields do the heavy lifting:
-
valuesis the application config, exactly what the service consumes. -
versionis an application-managed counter used for compare-and-swap. It is not the historyrev;versionis per key and visible to clients.
Enable history on the collection. This is what makes rollback possible without
a separate config archive:
from nonodb import NonoDB db = NonoDB(base_url="http://127.0.0.1:7878", token=TOKEN) configs = db.collection("configs") db.set_collection_history("configs", 100) History on a config collection is cheap. Configs are small and change far less
often than business documents. Retention 100 covers months of ordinary changes.
Validate before you write
The database stores JSON; it does not know your config schema. Validate in the
application before publishing, and treat a validation failure as a rejected
publish, not an exception that leaves half a document behind.
import jsonschema CHECKOUT_SCHEMA = { "type": "object", "required": ["max_items", "capture_mode"], "properties": { "max_items": {"type": "integer", "minimum": 1, "maximum": 1000}, "capture_mode": {"enum": ["automatic", "manual"]}, "countries": { "type": "array", "items": {"type": "string", "pattern": "^[A-Z]{2}$"}, }, "free_shipping_threshold": {"type": "integer", "minimum": 0}, }, "additionalProperties": False, } def validate_checkout(values: dict) -> None: jsonschema.validate(values, CHECKOUT_SCHEMA) Run the same validator on rollback targets. A six-month-old config may be valid
under the old schema and invalid today. Refusing an invalid rollback is better
than restoring a value the current code cannot handle.
If you do not want a Python dependency, a hand-written validator with explicit
range and enum checks is fine. The important part is that validation happens
before the write, in one place.
Publish with compare-and-swap
Two people editing config at the same time is the same lost-update problem as
any other document. A version guard turns it into a detectable conflict:
from datetime import datetime, timezone def bson_date(dt: datetime) -> dict: return {"$date": dt.isoformat()} def publish_config(key: str, values: dict, actor: str, expected_version: int): validate_checkout(values) # or a per-key validator updated = configs.find_and_modify( {"_id": key, "version": expected_version}, { "$set": { "values": values, "updated_by": actor, "updated_at": bson_date(datetime.now(timezone.utc)), }, "$inc": {"version": 1}, }, new=True, ) if updated is None: raise RuntimeError("config changed since you loaded it; reload and retry") return updated find_and_modify checks the version and applies the update in one writer
transaction. If another publish moved the version, nothing is written and the
caller gets None. There is no window between "the version is still 12" and
"write version 13".
This is the same guard used for collaborative editing, but the config workflow
is simpler: there is no field-level merge. A config publish is intentional and
whole-document. On conflict, reload, re-apply the intended change, publish
again.
Roll back to a previous version
The history snapshot stores the whole document, including the version field
from the time of that write. That gives you a direct mapping from a human
version number to a revision:
def find_config_version(key: str, version: int): for rev in configs.history(key, limit=100, include_docs=True): doc = rev.get("doc") or {} if doc.get("version") == version: return rev return None Rollback is a normal, validated publish of the old values, with metadata that
records what happened:
def rollback_config(key: str, to_version: int, actor: str, incident: str): config = configs.find_one({"_id": key}) if config is None: raise ValueError("config not found") target = find_config_version(key, to_version) if target is None: raise ValueError("target version is outside history retention") old_values = target["doc"]["values"] validate_checkout(old_values) restored = configs.find_and_modify( {"_id": key, "version": config["version"]}, { "$set": { "values": old_values, "updated_by": actor, "updated_at": bson_date(datetime.now(timezone.utc)), "rollback_from_version": config["version"], "rollback_to_version": to_version, "incident": incident, }, "$inc": {"version": 1}, }, new=True, ) if restored is None: raise RuntimeError("config changed during rollback; retry") return restored Why not restore the entire old document with a replacement update? Because that
would also revert version and lose the audit metadata. Write the old values
into a new version. The config history then reads:
v14 rollback to v12 alice INC-2026-021 v13 publish bob capture_mode: automatic -> manual v12 publish alice free_shipping_threshold: 19900 The bad config is still visible in history. That is correct: an audit trail
should not pretend the incident never happened. The current state is good, and
the path to it is explicit.
Make the rollback fast to trigger
An incident commander should not need a database client and a Python REPL. A
small admin endpoint is enough:
def rollback_endpoint(key: str, to_version: int, actor: str, incident: str): try: doc = rollback_config(key, to_version, actor, incident) return {"ok": True, "version": doc["version"], "values": doc["values"]} except ValueError as exc: return {"ok": False, "error": str(exc)} Add authorization in front of it. Config rollback is a privileged operation:
require a scope that ordinary application tokens do not have, and log the actor.
NonoDB's scopes are per database/collection, so the config collection can be
readable by services but writable only by the config admin role.
If you want a second pair of eyes, store approvals as documents and require the
approved target before the rollback write:
{ "_id": "INC-2026-021:checkout:v12", "incident": "INC-2026-021", "key": "checkout", "target_version": 12, "approved_by": ["alice@example.com", "bob@example.com"], "created_at": {"$date": "2026-01-14T10:20:00Z"} } A unique _id makes approval idempotent. The rollback endpoint checks for the
approval document before calling rollback_config. This is policy in the
application, not a database feature, but it composes cleanly with the versioned
config.
Automatic rollback on a failed health check
The fastest rollback is the one nobody has to trigger. A common pattern:
- Record
previous_versionbefore publishing. - Publish the new config.
- Run a short health check (synthetic checkout, error rate, queue depth).
- If it fails consistently for N checks, roll back to
previous_version.
def publish_with_guard(key: str, values: dict, actor: str, expected_version: int): before = configs.find_one({"_id": key}) published = publish_config(key, values, actor, expected_version) if not wait_for_healthy(attempts=3, delay_seconds=10): rollback_config( key, before["version"], actor="auto-rollback", incident="health-guard", ) raise RuntimeError("config rolled back after failed health check") return published Two warnings:
- Do not roll back on a single transient error. Require consecutive failures and a minimum observation window. Otherwise a blip causes a config flap.
- Do not fight a human. If an operator is actively rolling forward, an automatic rollback can make things worse. Set a short guard window and a flag that a manual action clears.
The rollback itself has the same CAS guard, so an automatic rollback cannot
overwrite a config that changed after the publish it is trying to undo.
Push the change to readers
Restoring the database value is only half the job; services must notice.
For services that read on every request, a find_one on the config document is
cheap. For services that cache config in memory, use events:
db.set_collection_events( "configs", enabled=True, ops=["insert", "update"], fields=["values"], include_before=True, include_after=True, ) A consumer reads _events with a checkpoint and invalidates its local cache.
The event is written in the same transaction as the config update, so no
successful publish is invisible to the event feed.
If you use the Python client's optional per-process read cache, remember that
writes from other processes are not observed until the TTL expires. For a
config that must be fresh within seconds, either disable the cache for that
collection's reads or set a short TTL and rely on the event feed for
invalidation.
What this design gives you
- Fast rollback. One validated write to the config document.
- No lost publishes. A version guard rejects concurrent overwrites.
- Audit for free. History records every publish and rollback with actor metadata.
- No redeploy. The application reads the restored values on the next read or cache invalidation.
- Selective scope. Services read config; only the admin role writes it.
What it does not give you
- Cross-document config atomicity. If one logical config spans several documents, a rollback of one does not automatically roll back the others. Keep one key per atomic unit, or use the immutable-version-and-pointer pattern in the next article.
- Schema migration. Rolling back values does not roll back code. Validate the old values against the current schema before restoring.
- Retention forever.
max_versionsis a count. If the good version is older than retention, history cannot help; use backups or an exported config archive. - Tamper-proofing. History is not WORM. An admin can still change data.
For the most common small-app case — one JSON blob, one bad publish, one fast
fix — a versioned document plus a CAS rollback is enough. It turns "restore the
previous configuration" from an incident procedure into a single operation.

