Event sign-ups¶
This tutorial deploys events, a JSON backend for meetups and workshops: an admin publishes events with a capacity,
anyone registers with a name and a contact, and registrants cancel with a private token. It is for developers who
want to see how SQL transactions, idempotency keys and streamed responses work inside a service.
Deno
What you build¶
- Public API: list events, read one, register with a name plus an email or a Telegram username, look up or cancel your own registration with the token you got at registration.
- Admin API (Bearer
ADMIN_TOKEN): create and update events, close and reopen registration, list registrations as JSON pages or download them as CSV.
The service is a plain JSON API, so any static page, bot or form can sit in front of it.
Why it fits the runtime. Registration is the classic race: two people take the last seat at the same moment.
Each service has its own SQLite database with a single writer, and sql.transaction runs the capacity check and
the insert as one unit, so there is no overbooking without any locking code of your own. An atomic kv.incr
counter on the client address the platform resolved (ctx.client.ip) throttles the public registration route. The
service holds no state between requests, the export streams in pages instead of building the file in memory, and
the admin token is a write-only secret.
Architecture¶
flowchart LR
C["Client (page, bot, form)"] -- "POST /events/{id}/registrations" --> EV["events (Deno, Form A)"]
A["Admin"] -- "Bearer ADMIN_TOKEN" --> EV
EV -- "throttle counter, Idempotency-Key replay" --- KV[("std:kv")]
EV -- "transaction: check + insert" --- SQL[("std:sql: events, registrations")]
EV -- "streamed text/csv" --> A
A registration goes through these steps:
- Count the request against the client address's budget for this minute (
kv.incr); over the budget it is429 rate_limitedwithRetry-After. - Validate the body (
name,emailand/ortelegram). - With an
Idempotency-Keyheader: if KV has an answer for that key, replay it. - In one SQL transaction: the event exists, is open and has not started, the contact is not registered yet, a seat is left; then insert.
- Return the registration and a token
evr_…once. Only the token's SHA-256 is stored.
Prerequisites¶
- A running node and a tenant key in
RT_KEY(see First run). 21ci(see Install), orbash,curlandjqforsample/scripts/*.sh.
| Name | Kind | Meaning |
|---|---|---|
ADMIN_TOKEN |
secret | Bearer token for the admin routes (at least 16 characters) |
CORS_ORIGIN |
env | Optional Access-Control-Allow-Origin value (an origin or *) for a browser frontend on another origin |
THROTTLE_PER_MINUTE |
env | Registrations one client address may send per minute, default 20; 0 turns the throttle off |
The admin token travels as Authorization: Bearer …. On a public service that header reaches the handler unchanged;
the platform removes it only when it carries one of its own tenant keys (Bearer rtk_…), so never use a tenant key
as ADMIN_TOKEN.
Deploy it¶
cd sample/apps/events
RT_COMPILE=eager ../../scripts/deploy.sh src events
SVC=$(../../scripts/svc-id.sh events)
ADMIN=$(openssl rand -hex 24)
jq -nc --arg v "$ADMIN" '{value: $v}' | curl -sS -X PUT -H "Authorization: Bearer $RT_KEY" \
-H 'Content-Type: application/json' --data-binary @- "$RT_API/v1/services/$SVC/secrets/ADMIN_TOKEN"
The per-address throttle is on by default. On a public deployment, also set the service's ingress rate limit as a global cap:
Try it¶
B=http://127.0.0.1:8080/s/events
curl -sS -X POST $B/events -H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
-d '{"title": "Rust meetup", "starts_at": "2026-11-20T18:00:00+05:00", "capacity": 40, "location": "IT Park"}'
curl -sS $B/events
curl -sS -X POST $B/events/1/registrations -H 'Content-Type: application/json' -H "Idempotency-Key: $(uuidgen)" \
-d '{"name": "Ada", "telegram": "@ada_l"}' # keep the returned token
curl -sS -X DELETE $B/registration -H "X-Registration-Token: evr_…"
curl -sS -H "Authorization: Bearer $ADMIN" -o reg.csv $B/events/1/registrations.csv
starts_at must be ISO 8601 with an offset (…+05:00 or …Z) and in the future; responses use UTC.
| Method and path | Auth | Answer |
|---|---|---|
GET /events |
none | {events: [event]}, upcoming by start time (?past=1 lists all) |
GET /events/{id} |
none | the event with registered, spotsLeft, registrationOpen |
POST /events/{id}/registrations |
none | 201 {registration, token}; 409 event_full, already_registered, event_closed, event_started; 429 rate_limited with Retry-After |
GET /registration |
X-Registration-Token |
{registration, event} |
DELETE /registration |
X-Registration-Token |
{registration} with status: cancelled; repeating it is fine |
POST /events |
admin | 201 event |
PATCH /events/{id} |
admin | event; 409 capacity_below_registered |
POST /events/{id}/close, /reopen |
admin | event |
GET /events/{id}/registrations |
admin | {event, registrations, next}; ?status=confirmed\|cancelled\|all&limit=&after= |
GET /events/{id}/registrations.csv |
admin | text/csv download |
Errors are {"error": {"code", "message"}}; validation errors are 400 validation_failed.
How the code works¶
src/main.ts holds the handler and all SQL. src/validate.ts (input rules), src/csv.ts (CSV encoding) and
src/http.ts (JSON, auth and token helpers) are pure, so the unit tests load them without the runtime.
Schema: partial unique indexes¶
let schemaReady = false;
async function ensureSchema() {
if (schemaReady) return;
const found = await execSql("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'events_starts'");
if (found.rows.length === 0) {
await sql.batch([
`CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',
location TEXT NOT NULL DEFAULT '', starts_at INTEGER NOT NULL, capacity INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)`,
`CREATE TABLE IF NOT EXISTS registrations (
id INTEGER PRIMARY KEY AUTOINCREMENT, event_id INTEGER NOT NULL REFERENCES events (id),
name TEXT NOT NULL, email TEXT, telegram TEXT, token_hash TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'confirmed' CHECK (status IN ('confirmed', 'cancelled')),
created_at INTEGER NOT NULL, cancelled_at INTEGER)`,
// One active registration per contact and event; a cancelled one does not block a new one.
`CREATE UNIQUE INDEX IF NOT EXISTS reg_email ON registrations (event_id, email)
WHERE status = 'confirmed' AND email IS NOT NULL`,
`CREATE UNIQUE INDEX IF NOT EXISTS reg_telegram ON registrations (event_id, telegram)
WHERE status = 'confirmed' AND telegram IS NOT NULL`,
`CREATE INDEX IF NOT EXISTS reg_event ON registrations (event_id, status, id)`,
`CREATE INDEX IF NOT EXISTS events_starts ON events (starts_at)`,
], "write");
}
schemaReady = true;
The two partial unique indexes allow one confirmed registration per email and per Telegram username for each
event. A cancelled registration no longer counts, so the same person can register again. The schema is created
read-first: the CREATE batch runs only when the last index is missing, so ordinary requests never write DDL.
No overbooking: one transaction¶
type RegisterOutcome = { status: 201; id: number } | { status: 404 | 409; code: string; message: string };
async function insertRegistration(eventId: number, input: RegistrationInput, tokenHash: string): Promise<RegisterOutcome> {
// One transaction: the capacity check and the insert cannot interleave with another registration.
return await sql.transaction(async (tx: SqlTx) => {
const exec: Exec = (t, a) => tx.execute(t, a);
const ev = await one(exec, "SELECT status, capacity, starts_at FROM events WHERE id = ?", [eventId]);
if (!ev) return { status: 404, code: "not_found", message: "no such event" };
if (ev.status !== "open") return { status: 409, code: "event_closed", message: "registration is closed" };
if (Number(ev.starts_at) <= nowSec()) return { status: 409, code: "event_started", message: "the event has started" };
const dup = await one(
exec,
"SELECT 1 AS x FROM registrations WHERE event_id = ? AND status = 'confirmed' AND (email = ? OR telegram = ?)",
[eventId, input.email, input.telegram],
);
if (dup) return { status: 409, code: "already_registered", message: "this contact is already registered" };
const taken = await one(exec, "SELECT COUNT(*) AS n FROM registrations WHERE event_id = ? AND status = 'confirmed'", [eventId]);
if (Number(taken?.n) >= Number(ev.capacity)) return { status: 409, code: "event_full", message: "no spots left" };
const r = await exec(
"INSERT INTO registrations (event_id, name, email, telegram, token_hash, created_at) VALUES (?, ?, ?, ?, ?, ?)",
[eventId, input.name, input.email, input.telegram, tokenHash, nowSec()],
);
return { status: 201, id: Number(r.lastInsertRowid) };
});
The status check, the duplicate check, the seat count and the insert run inside sql.transaction. It commits when
the callback resolves and rolls back when it throws. SQLite has a single writer per database, so two concurrent
registrations for the last seat are serialized: the second one sees the first one's row and gets 409 event_full.
The partial unique indexes are the backstop if the duplicate check were ever wrong. A transaction is capped at 5 s
(sql_timeout), which this short one never approaches.
Safe retries with Idempotency-Key¶
A client on a bad network may send the same registration twice. With an Idempotency-Key header the first answer is
stored in KV for 24 hours and replayed for the retry:
// The notifier service (sample/apps/events/notify), called over RPC when NOTIFY_SERVICE names it.
// Best effort: the registration stands when the notifier is missing or fails, and the failure is logged.
interface Notifier {
confirmRegistration(args: { eventId: number; registrationId: number; name: string }): Promise<{ receipt: string }>;
}
async function notifyRegistration(eventId: number, registrationId: number, name: string): Promise<string | null> {
const target = env("NOTIFY_SERVICE");
if (!target) return null;
try {
const out = await (services.bind(target) as unknown as Notifier).confirmRegistration({ eventId, registrationId, name });
return out.receipt;
} catch (e) {
console.error(`confirmation not sent: ${(e as { code?: string }).code ?? "error"}`);
return null;
}
}
async function register(eventId: number, req: Request): Promise<Response> {
const idem = req.headers.get("idempotency-key");
if (idem !== null && !isValidIdempotencyKey(idem)) return error(400, "invalid_idempotency_key", "8-128 characters of A-Z a-z 0-9 _ -");
const body = await readJson(req, MAX_BODY);
if (!body.ok) return body.response;
const input = validateRegistration(body.value);
if (!input.ok) return error(400, "validation_failed", input.error);
// A retried request with the same Idempotency-Key gets the first answer (token included) for 24 h.
const fingerprint = await sha256Hex(JSON.stringify([eventId, input.value]));
- The KV key is the SHA-256 of the client's key, so arbitrary client input never becomes a KV key.
- The fingerprint ties the key to the request body: the same key with a different body is
422 idempotency_mismatch. - A replay carries the header
idempotent-replayed: trueand the same token as the first answer. ttlSeconds: 86400lets the store clean itself up; expired keys read asnull.
Tokens are stored as hashes¶
The registration token is evr_ plus 32 random bytes in base64url. Only its SHA-256 goes into the database, so a
database export cannot be used to cancel anyone's registration:
// `prefix` + base64url of `bytes` random bytes (32 bytes = 43 characters).
export function randomToken(prefix: string, bytes = 32): string {
const b = crypto.getRandomValues(new Uint8Array(bytes));
return prefix + btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
// Tokens are stored only as their SHA-256, so a copy of the database cannot be used to act on them.
export async function sha256Hex(s: string): Promise<string> {
const d = new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(s)));
return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
}
Cancellation looks the registration up by that hash, again in a transaction, and is idempotent:
const result = { registration: registrationView(reg!), token, receipt };
if (idemKey) await kv.set(idemKey, { fingerprint, status: 201, body: result }, { ttlSeconds: IDEMPOTENCY_TTL });
return json(result, 201);
}
async function tokenHashOf(req: Request): Promise<string | null> {
const t = req.headers.get("x-registration-token") ?? "";
return isValidRegistrationToken(t) ? await sha256Hex(t) : null;
}
async function myRegistration(req: Request): Promise<Response> {
const hash = await tokenHashOf(req);
if (!hash) return error(401, "invalid_token", "send the token from registration in X-Registration-Token");
const reg = await one(execSql, "SELECT * FROM registrations WHERE token_hash = ?", [hash]);
if (!reg) return error(404, "not_found", "no registration for this token");
const ev = await findEvent(Number(reg.event_id));
return json({ registration: registrationView(reg), event: ev ? eventView(ev) : null });
}
async function cancelRegistration(req: Request): Promise<Response> {
const hash = await tokenHashOf(req);
Streaming the CSV export¶
The export never holds the whole file in memory. A ReadableStream with a pull callback reads 1,000 rows per pull,
and the runtime sends each chunk as soon as it is produced:
async function listRegistrations(id: number, url: URL): Promise<Response> {
const ev = await findEvent(id);
if (!ev) return error(404, "not_found", "no such event");
const status = url.searchParams.get("status") ?? "all";
const limit = Number(url.searchParams.get("limit") ?? "500");
const after = Number(url.searchParams.get("after") ?? "0");
if (!REG_STATUS.has(status)) return error(400, "invalid_status", "status is confirmed, cancelled or all");
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) return error(400, "invalid_limit", "limit is 1-1000");
if (!Number.isInteger(after) || after < 0) return error(400, "invalid_after", "after is a registration id");
const r = await execSql(
"SELECT * FROM registrations WHERE event_id = ? AND (? = 'all' OR status = ?) AND id > ? ORDER BY id LIMIT ?",
[id, status, status, after, limit],
);
const regs = objects(r).map(registrationView);
const next = regs.length === limit ? regs[regs.length - 1].id : null;
return json({ event: eventView(ev), registrations: regs, next });
}
// Streamed in pages of 1,000 rows: the export of a 100,000-seat event never sits in memory.
async function exportCsv(id: number): Promise<Response> {
const ev = await findEvent(id);
if (!ev) return error(404, "not_found", "no such event");
const enc = new TextEncoder();
let after = 0;
let started = false;
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
if (!started) {
started = true;
controller.enqueue(enc.encode(UTF8_BOM + csvLine(["id", "name", "email", "telegram", "status", "registered_at", "cancelled_at"])));
return;
}
try {
const page = objects(await execSql(
"SELECT * FROM registrations WHERE event_id = ? AND id > ? ORDER BY id LIMIT 1000",
[id, after],
));
if (page.length === 0) return controller.close();
after = Number(page[page.length - 1].id);
A response body can be up to 100 MB, see Limits. The file starts with a UTF-8 BOM so spreadsheet apps show Cyrillic and Uzbek names correctly, and every cell goes through a formula-injection guard:
// RFC 4180 CSV with a guard against formula injection: a cell that starts with = + - @ tab or CR
// would be evaluated by Excel / LibreOffice / Sheets, so string cells like that get a leading '.
export function csvCell(v: unknown): string {
if (v === null || v === undefined) return "";
let s = typeof v === "string" ? v : String(v);
if (typeof v === "string" && /^[=+\-@\t\r]/.test(s)) s = `'${s}`;
return /[",\r\n]|^\s|\s$/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
// One record with its CRLF line ending.
export function csvLine(cells: unknown[]): string {
return cells.map(csvCell).join(",") + "\r\n";
}
// Prepended once to a file, so Excel reads non-Latin names as UTF-8.
export const UTF8_BOM = String.fromCharCode(0xfeff);
Routing, admin auth, throttle and CORS¶
A small table maps method and path patterns to handlers. Admin routes check the Bearer token in constant time.
Routes with a throttle scope (only POST /events/{id}/registrations) are counted against the client address next,
and only then is the schema checked:
return csvLine([v.id, v.name, v.email, o.telegram ?? null, v.status, v.createdAt, v.cancelledAt]);
}).join("")));
} catch (e) {
console.error("csv export:", errorText(e));
controller.error(e);
}
},
});
return new Response(stream, {
headers: {
"content-type": "text/csv; charset=utf-8",
"content-disposition": `attachment; filename="event-${id}-registrations.csv"`,
"cache-control": "no-store",
},
});
}
// ---------------------------------------------------------------------------------- routing
type Route = {
{ method: "GET", re: /^\/events\/(\d{1,12})\/registrations$/, admin: true, run: (m, _r, u) => listRegistrations(Number(m[1]), u) },
{ method: "GET", re: /^\/events\/(\d{1,12})\/registrations\.csv$/, admin: true, run: (m) => exportCsv(Number(m[1])) },
{ method: "GET", re: /^\/registration$/, admin: false, run: (_m, r) => myRegistration(r) },
{ method: "DELETE", re: /^\/registration$/, admin: false, run: (_m, r) => cancelRegistration(r) },
];
// Optional CORS for a frontend on another origin (CORS_ORIGIN=https://events.example.com or *).
function withCors(res: Response): Response {
const origin = env("CORS_ORIGIN");
if (!origin) return res;
const h = new Headers(res.headers);
h.set("access-control-allow-origin", origin);
h.set("access-control-allow-headers", "authorization, content-type, idempotency-key, x-registration-token");
h.set("access-control-allow-methods", "GET, POST, PATCH, DELETE");
h.set("access-control-expose-headers", "idempotent-replayed, content-disposition, retry-after");
if (origin !== "*") h.append("vary", "origin");
return new Response(res.body, { status: res.status, headers: h });
}
async function route(req: Request, ctx: Ctx): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname.replace(/\/+$/, "") || "/";
if (req.method === "OPTIONS") return new Response(null, { status: 204 });
if (path === "/") {
return json({
service: "events",
public: ["GET /events", "GET /events/{id}", "POST /events/{id}/registrations", "GET /registration", "DELETE /registration"],
admin: ["POST /events", "PATCH /events/{id}", "POST /events/{id}/close", "POST /events/{id}/reopen",
"GET /events/{id}/registrations", "GET /events/{id}/registrations.csv"],
});
}
const matching = ROUTES.filter((r) => r.re.test(path));
if (matching.length === 0) return error(404, "not_found", "no such route");
const r = matching.find((x) => x.method === req.method);
if (!r) return error(405, "method_not_allowed", "method not allowed", { allow: matching.map((x) => x.method).join(", ") });
if (r.admin) {
const denied = await requireAdmin(req, env("ADMIN_TOKEN"));
The handler is a Form A default function: export default async function (req, ctx). withCors adds CORS headers
only when CORS_ORIGIN is set. An unknown method on a known path gets 405 with an allow header.
A per-address throttle with kv.incr¶
src/throttle.ts counts requests per client address in fixed one-minute windows. The handler passes kv.incr in,
so the module has no std:* import and the unit tests load it as it is:
export function throttleKey(scope: string, ip: string, w: Window): string {
return `throttle/${scope}/${clientBucket(ip)}/${w.start}`;
}
export interface Verdict {
allowed: boolean;
remaining: number;
retryAfter: number; // seconds
}
// `count` = what kv.incr returned: the requests of this window, this one included.
export function decide(count: number, limit: number, w: Window): Verdict {
return { allowed: count <= limit, remaining: Math.max(0, limit - count), retryAfter: w.resetIn };
}
// Counts the request and answers 429 once the address has used its budget for this minute; null
// lets the request through: allowed, throttle off, no client address (not an HTTP request), or the
// store failed (logged; availability over strictness).
export async function throttle(
incr: Incr,
scope: string,
ip: string | undefined,
limit: number,
nowMs = Date.now(),
): Promise<Response | null> {
if (!ip || limit <= 0) return null;
const w = windowOf(nowMs);
let count: number;
try {
count = Number(await incr(throttleKey(scope, ip, w), 1, { ttlSeconds: WINDOW_SECONDS + 5 }));
} catch (e) {
console.warn(`throttle store: ${errorText(e)}`);
return null;
}
const v = decide(count, limit, w);
if (v.allowed) return null;
return error(429, "rate_limited", `too many requests from this address; try again in ${v.retryAfter} s`, {
"retry-after": String(v.retryAfter),
});
}
kv.incr(key, 1, { ttlSeconds })adds 1 and returns the new value in one atomic step on the service's single SQLite writer, so parallel requests never share a count. The TTL applies when the call creates the key, so each window's counter expires on its own.ctx.client.ipis the address the platform resolved for the HTTP request, behindingress.trusted_proxies. A client-sentx-rt-client-ipis removed first, so the address cannot be spoofed. IPv6 addresses count per /64.ctx.clientexists only for thehttptrigger. Without it, or withTHROTTLE_PER_MINUTE=0, the throttle lets the request through, and so it does when the KV store fails (availability over strictness, logged).- A fixed window admits up to twice the limit across a minute boundary, and people behind one NAT share a budget. Keep the service's ingress rate limit as the global cap.
Test it¶
Unit tests. test/validate.test.ts covers start-time parsing (an offset is required), text cleanup, event
create and patch validation, email and Telegram normalization, registration validation, token and idempotency-key
formats, and CSV escaping with the formula guard. test/throttle.test.ts covers the throttle with a fake incr.
Smoke test. smoke.sh deploys events-smoke and runs the whole flow against a node: admin auth, starts_at
without an offset, an event with 2 seats, an idempotent retry (same token, idempotent-replayed: true), the same key
with another body (422), a case-insensitive duplicate email, event_full, cancel and cancel again, the freed seat
being taken, capacity below registrations, close and reopen, the JSON list with a status filter, the CSV export
(5 lines, the formula guard, the Telegram column), and finally the throttle: with THROTTLE_PER_MINUTE=15 it sends
registrations until one is answered 429 rate_limited with a Retry-After, and checks that reads are not
throttled.
Notes and limits¶
- Lists return at most 200 events; registrations page by id (
next,limitup to 1,000). Capacity is at most 100,000. - Contacts are not verified and no email is sent. Plug in a mail API through
fetchif you need confirmation. - The idempotency store keeps the first answer, token included, for 24 hours in the service's own KV.
Ideas to extend it¶
- Add a waitlist: when an event is full, insert with
status = 'waitlisted'and promote the first one inside the cancel transaction. - Send a confirmation email through an outside mail API with
fetch, from a queue message so a slow mail provider does not slow down registration. - Send reminders the day before an event with an interval schedule and a
scheduledhandler (Form B). - Put a static registration page in front of it on the same service, as Live queue does.
Where the code lives¶
sample/apps/events/ in the runtime repository: src/ (the service), test/ (unit tests), smoke.sh and a
README.
See also¶
- Storage: KV, SQL and blob per service
- Deno services
- Guest API reference:
sql.transaction,kv.setwith a TTL