← All lessons/Working with Records
9
Working with Records

Per-Record TTL

How TTL works under the hood, the sweeper cycle, and correct usage patterns.

Prerequisite: Lesson 5 complete

What you'll learn

  • ttl_ms field injects _expires_at_ms into payload before storage
  • TTL sweeper: 60-second cycle, Weak<AgentRegistry> reference
  • Good TTL use cases: sessions, OTPs, idempotency keys, rate limiters
  • Bad TTL use cases: compliance data, financial records
  • Write a 65-second TTL record and observe it expire
Challenge

Create a password_reset_tokens agent. Write a token with 15-minute TTL. Verify 404 after sweeper runs.

Interactive Walkthrough

What you'll learn

How TTL works under the hood, the sweeper cycle, and patterns for using TTL correctly.

How TTL works

When you write a record with ttl_ms: 3600000, the engine injects _expires_at_ms into the payload before storing:

{
  "session_token": "tok_xyz",
  "_expires_at_ms": 1751903600000
}

A background sweeper runs every 60 seconds. It scans the strand, finds records where current_time_ms > _expires_at_ms, and writes tombstones for them. The sweeper holds a Weak<AgentRegistry> reference — it never prevents the process from shutting down cleanly.

Good use cases for TTL

Use caseTTL
Auth session tokens1–24 hours
Password reset links15–30 minutes
Idempotency keys24 hours
Cache entriesMinutes to hours
Rate limit counters1 minute
OTP codes5–10 minutes

Bad use cases for TTL

Do not use TTL for records you want to audit later. Once the tombstone is written, the original payload is logically hidden (though still on disk). For compliance data, keep records permanently and use soft-delete only when legally required.

Check if a record has expired

# Will return 404 if TTL has passed and sweeper has run
curl -s http://localhost:7475/v1/agents/sessions/records/<HASH> \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY"

Write a short-TTL record and watch it expire

`bash # Expires in 65 seconds curl -s -X POST http://localhost:7475/v1/agents/sessions/write \ -H "Content-Type: application/json" \ -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \ -d '{"payload": {"token": "short_lived"}, "ttl_ms": 65000}' \ | python3 -m json.tool

# Save the content_hash, wait 70 seconds, then try to fetch it sleep 70 curl -s http://localhost:7475/v1/agents/sessions/records/<HASH> \ -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" # → 404 Not Found `

Challenge

Create a password_reset_tokens agent. Write a token with 15-minute TTL. Verify it is readable immediately. Verify it returns 404 after the sweeper runs.

---

← Previous
Lesson 8: Batch Writes
Next →
Lesson 10: Schema Validation