Keep short-lived values
Store drafts and counters under a key with an expiry, scoped to the tenant, on a file in development and Redis in production.
Status Status is where the work is: Planned (in a milestone, not started), Building (tickets in progress), Preview (usable, may change), then the stability it ships at.
Stability The promise an interface ships with.
- Stable Follows semantic versioning; breaking changes need a new major, 12 months of overlap and a codemod.
- Beta Usable in production; may change before it becomes stable.
- Experimental May change or go away; needs an explicit opt-in in main.yaml.
You will keep a draft for a day and count events in a fixed window, using kv on a local file first and Redis when you deploy. It takes about 10 minutes and needs no account for the local part.
You need
- A project with
main.yaml. - For production: a Redis URL as a secret, for example
REDIS_URL.
1. Store and read a value
kv:
driver: local
file: .mainsdk/kv.json # optional: keeps values across restartsimport { kv } from "mainsdk";
const userId = "u_1"; // the signed-in user
await kv.set(`draft:${userId}`, { step: 2 }, { ttl: "1d" });
const draft = await kv.get<{ step: number }>(`draft:${userId}`); // null once it expiresYou should see get return the value now and null after a day.
2. Count in a window
import { kv } from "mainsdk";
const userId = "u_1";
const n = await kv.incr(`hits:${userId}`, { ttl: "1m" }); // 1, 2, 3 ... then a new windowThe expiry is set when the key is created, so the window doesn't move. Use limits when you want a refusal with Retry-After.
3. Move to Redis
kv:
driver: redis
redis: { url: secret:REDIS_URL, prefix: myapp }Add the Redis host to network.allow, or let mainsdk discover list it. Your calls don't change. Values are not copied from the file.
Ask your agent
Goal: keep onboarding drafts for a day and count invites per hour.
Touch: main.yaml (kv section), the draft and invite code, one test with the fake clock.
Rules: pass a ttl on every draft and counter; never put personal data in a kv value; read the Redis URL from a secret.
Verify: pnpm mainsdk check && pnpm test
Never weaken or skip a check; fix the finding it names.Next
Was this page helpful?