Skip to content
Playground(another site)

Expire sessions with a Cache

Resolve a session token to its user for a bounded lifetime, expiring entries automatically without writing a sweep, and report how many sessions are currently live.

commons tokens
---
A session token — an opaque, bounded handle that addresses a cache entry. It is
non-empty and length-capped, so a malformed token is rejected at the boundary
before any cache lookup runs.
---
type Token = String where NonEmpty && MaxLength(128)
---
The authenticated user a live token resolves to.
---
type UserId = String where NonEmpty
Open the full project(opens GitHub in a new tab)

This example reaches Workers-only shapes (storage bindings, agents, or cron), so it runs with bynk dev rather than in the browser playground. See Install to get started.

agent Sessions is keyed by a shard string and holds one store: live: Cache[Token, UserId] @ttl(30.minutes). A Cache is a Map whose entries expire on their own — each put (re)starts the 30-minute clock, an entry past its TTL reads as None, and expired entries are reaped at the next commit, so size counts only live entries with no separate sweep to write. The boundary types are refined in commons tokens: Token is NonEmpty && MaxLength(128), UserId is NonEmpty, so a malformed token is rejected before any cache lookup.

Time is honest. Eviction consults the clock, so every cache operation except remove declares given Clock — login, whoami, and active all carry it, while logout (an idempotent live.remove) does not. The dependency is visible in each signature, and a mocked clock would make expiry deterministic.

The session travels in a cookie. POST /sessions mints an unguessable token with Random.bytes(16).toBase64Url(), starts the session under it, and answers Created("ok").withCookie(Cookie { name: "__Host-sid", value: text, maxAge: Some(30.minutes) }). A Cookie’s defaults are the safe ones: Secure, HttpOnly, SameSite=Lax and Path=/, and the __Host- prefix, which binds the cookie to this origin, is checked at compile time. GET /me reads it back through a typed cookies: SessionCookies record whose field is @name("__Host-sid") sid: Option[Token] (a hyphenated name cannot be a field name, so @name gives the field the key the browser sends), so a malformed value is refused with a 400 by the Token refinement before the handler runs. POST /logout reads the raw cookies: RequestCookies view instead, so it clears the cookie whatever it holds, even a value the typed record would refuse. Whoami answers Unauthorized for an unknown or expired token, and logout ends the session and clears the cookie with clearCookie. GET /sessions still reports the live count.