Every small product eventually grows the same little subsystem: one-time
invite links
.

A teammate clicks "Invite", we generate a token, send a URL, and the link must
work exactly once and stop working after seven days. It also has to be
auditable — "who invited whom, and when was the link used?" — because support
will ask.

The classic stack for this is three moving parts:

  1. Redis with SETEX invite:<token> 604800 <payload> for the expiry.
  2. Postgres for the durable invite record and the audit trail.
  3. A cron job that deletes stale rows so the table does not grow forever.

That is a cache, a database, and a scheduler for a feature that stores maybe a
few thousand rows. On a 1 GB VM it is also three more things that can page you
at 2 a.m.

This post rebuilds the feature with one process: NonoDB, a single Rust
daemon that owns LMDB files and speaks HTTP/JSON. The whole thing fits in the
same mental model as SQLite, but with document semantics, TTL, and per-document
history built in.

The requirements, written down

Before choosing anything, I wrote the actual contract:

  • A token is a random 32-byte value, stored hashed.
  • Default lifetime: 7 days.
  • Some invites are shorter — a support re-invite should die after 1 hour.
  • A token can be consumed at most once, even if two requests race.
  • Consuming a token must be atomic with marking it used.
  • We keep the invite record for audit, but not forever.
  • The whole service must run on a 1 vCPU / 1 GB VM next to the app.

The important line is number four. Expiry is not authorization. A TTL is a
garbage collector, not a lock. If two requests arrive at the same time, "is it
expired?" followed by "mark it used" is a race unless the check and the write
happen in one transaction.

Run the daemon

NonoDB publishes Linux amd64/arm64 images. Pin an exact version in
production; latest should be a deliberate choice, not an accident.

export NONODB_AUTH_FILE="$PWD/nonodb-auth.json" nonodb-cli auth init export TOKEN=$(nonodb-cli auth token create admin) docker volume create nonodb-data docker run -d --name nonodb \ -e NONODB_AUTH_FILE=/etc/nonodb/auth.json \ -e NONODB_TCP=0.0.0.0:7878 \ -p 127.0.0.1:7878:7878 \ --group-add "$(id -g)" \ -v "$NONODB_AUTH_FILE:/etc/nonodb/auth.json:ro" \ -v nonodb-data:/var/lib/nonodb \ ghcr.io/essmos/nonodb:0.26.0 
curl -s http://127.0.0.1:7878/healthz 

The daemon runs as an unprivileged user. TCP requires the auth registry; the
Unix socket is the trusted local channel. For a single-host app, mounting the
socket into the app container is even simpler, and there is no bearer token to
rotate.

Create the collection once

NonoDB collections can carry a default TTL and a history retention setting.
Both are opt-in.

from nonodb import NonoDB db = NonoDB(base_url="http://127.0.0.1:7878", token=TOKEN) invites = db.collection("invites") db.create_collection( "invites", ttl_seconds=7 * 24 * 3600, # default: 7 days ttl_purge_history=False, # keep revisions for audit ) db.set_collection_history("invites", 20) 

Two details matter here:

  • The collection default applies to documents inserted after it is set. It does not rewrite existing documents.
  • ttl_purge_history=False means an expiry leaves a delete tombstone in history instead of erasing the revisions. For an audit trail, that is what we want, at the cost of some disk.

There is no cron entry and no cleanup container.

Insert an invite with a per-document override

The default is seven days, but the support workflow needs one hour. The reserved
top-level _ttl field overrides the collection default for that document:

import hashlib import secrets from datetime import datetime, timedelta, timezone def bson_date(value: datetime) -> dict: """Wrap an instant in MongoDB Extended JSON for the HTTP API.""" return {"$date": value.isoformat()} def create_invite(team_id: str, email: str, ttl_seconds: int = 7 * 24 * 3600): raw = secrets.token_urlsafe(32) token_hash = hashlib.sha256(raw.encode()).hexdigest() now = datetime.now(timezone.utc) invites.insert({ "_id": token_hash, # lookup by hash, never store the raw token "team_id": team_id, "email": email.lower(), "used": False, "created_by": "dashboard", "expires_at": bson_date(now + timedelta(seconds=ttl_seconds)), "_ttl": ttl_seconds, # cleanup window, not the auth check }) return raw # Support re-invite: valid for one hour. raw_token = create_invite("team_42", "new@example.com", ttl_seconds=3600) 

_ttl is metadata: it is stored outside the document and is not returned by
reads. An update that does not mention _ttl preserves the current expiry, so
"resend invite" can extend or shorten the window explicitly:

def extend_invite(token_hash: str, ttl_seconds: int = 7 * 24 * 3600): new_deadline = datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds) invites.update( {"_id": token_hash}, {"$set": {"_ttl": ttl_seconds, "expires_at": bson_date(new_deadline)}}, ) 

Consume the invite exactly once

This is where the Redis-plus-Postgres version needed a transaction or a Lua
script. In NonoDB, find_and_modify selects one document, applies the update,
and returns the image — all inside the single writer transaction.

from datetime import datetime, timezone def consume_invite(raw_token: str) -> dict | None: token_hash = hashlib.sha256(raw_token.encode()).hexdigest() now = datetime.now(timezone.utc) old = invites.find_and_modify( {"_id": token_hash, "used": False, "expires_at": {"$gt": bson_date(now)}}, {"$set": {"used": True, "used_at": bson_date(now)}}, new=False, projection={"_id": 1, "team_id": 1, "email": 1, "used": 1}, ) return old # None means: unknown, already used, expired, or swept 

Two concurrent requests cannot both receive the invite. The second one matches
nothing, because the first transaction already set used: true. There is no
read-modify-write gap in application code, and no distributed lock.

The Python client passes the Extended JSON object through unchanged. Over raw
HTTP, NonoDB also accepts numeric milliseconds and RFC 3339 strings with Z or
a numeric offset; naive local times are rejected as ambiguous.

TTL is cleanup, not the security boundary

This deserves its own section because it is the most common design mistake with
any TTL feature, including Redis.

NonoDB TTL is eventual. A document stays readable until the background
maintenance worker sweeps it, normally within a few seconds of expiry. That is
perfect for garbage collection and terrible as the only check for "is this link
still valid?"

So the application contract has two checks, and the find_and_modify filter
above already carries both:

  1. used == false — enforced atomically by the write transaction.
  2. expires_at > now — the hard deadline, independent of cleanup timing.

The TTL setting exists so that the collection does not grow forever, and so that
support does not see year-old invites in the GUI. It is not SETNX.

If a document somehow survives long past its deadline, the expires_at filter
still rejects it. TTL remains the janitor, not the bouncer.

The audit trail is already there

Because history is enabled on the collection, the insert and the consume are
recorded as revisions in the same LMDB transaction as the current document.
There is no second write path to forget.

revisions = invites.history(token_hash, limit=10, include_docs=True) for rev in revisions: print(rev["rev"], rev["op"], rev["at"], rev.get("doc", {}).get("used")) 

rev is a global monotonic revision ID. For one document, revisions are ordered
but not necessarily consecutive — another document's write can take a number in
between. get_version(token_hash, rev) returns one exact revision, or None if
retention has pruned it.

The retention setting caps revisions per document at 20. For invites that is
plenty: created, maybe extended once, consumed, expired.

A real audit export can then be a single aggregation over the collection or a
batch of reads, without joining two databases.

What about the "expired invites" dashboard?

Support wants a count of live invites per team. With a secondary index on
team_id this is a normal indexed query:

invites.create_index(field="team_id") 
live = invites.count({"team_id": team_id, "used": False}) 

count({}) is O(1) in NonoDB; filtered counts use the index when the filter
matches it. For a grouped report:

list(invites.aggregate([ {"$match": {"used": False}}, {"$group": {"_id": "$team_id", "live": {"$sum": 1}}}, {"$sort": {"live": -1}}, {"$limit": 20}, ])) 

No separate analytics store, no nightly rollup.

What this costs

The feature now has:

  • one daemon,
  • one data volume,
  • one collection with a TTL default and history retention,
  • no cache server,
  • no cron job,
  • no cleanup Lambda.

On a small VM the idle daemon is in the single-digit-megabyte range, which is
the main reason I reached for it instead of adding another service. Backups are
a single LMDB directory, and the daemon supports native or restic backups with
encryption if the data ever leaves the box.

When I would not do this

Honesty is useful in a tutorial:

  • If the app already runs Postgres and the team knows it well, a partial unique index plus a scheduled DELETE is a perfectly good solution. NonoDB wins when you do not want to operate a second database server.
  • If you need cross-collection transactions across many entities, a relational database with real foreign keys is still the safer default.
  • If the token volume is in the tens of millions per day, measure first. NonoDB serializes writes through one writer thread, which is ideal for this workload but not a horizontally sharded write firehose.

For the actual shape of this problem — a few thousand short-lived records, one
small VM, one process, atomic consumption, and an audit trail — one binary is
easier to reason about than three services.

Try it

docker run --rm -it \ -e NONODB_AUTH_FILE=/etc/nonodb/auth.json \ -e NONODB_TCP=0.0.0.0:7878 \ -p 127.0.0.1:7878:7878 \ -v "$PWD/nonodb-auth.json:/etc/nonodb/auth.json:ro" \ -v nonodb-data:/var/lib/nonodb \ ghcr.io/essmos/nonodb:0.26.0 

The full API surface used here — create_collection, _ttl, find_and_modify,
history, aggregate — is in the NonoDB docs. If you want the next article in
this series, it will take the same daemon and build a job queue with leases and
retries, again without Redis.

NonoDB is MIT-licensed. I am writing this series while exploring it; the
examples above are run against the 0.26 release.