Session Manager With Sliding Expiry
Implement the session store behind a login system. Time is passed in explicitly as whole seconds, so the behaviour is deterministic.
new SessionManager(ttl): sessions livettlseconds after their last use.createSession(userId, now): returns a new token, unique among every token ever issued. A user may hold several sessions at once.validate(token, now): returns the session'suserIdwhen the token exists and has not expired, otherwisenull. A successful validation resets the expiry tonow + ttl.invalidate(token): revokes the token; returns whether it existed.cleanup(now): removes every expired session from storage and returns how many it removed. It must run in O(n) for n stored sessions.
A session created or last validated at time t is valid while now < t + ttl.
sm = new SessionManager(300)
tok = sm.createSession("user_7", 0)
sm.validate(tok, 200) -> "user_7" // and the expiry moves to 500
sm.validate(tok, 499) -> "user_7" // expiry moves to 799
sm.validate(tok, 799) -> null // expired
sm.cleanup(800) -> 1Hints
Hint 1
A map from token to { userId, expiresAt } covers everything except an efficient cleanup; a counter or a random id with a uniqueness check gives the tokens.
Hint 2
Expire lazily too: a validate that finds an expired token can delete it on the spot instead of leaving it for cleanup.
Hint 3
This is an LRU cache keyed by time. Keep the sessions in a list ordered by expiry (a validation moves its session to the tail), and cleanup walks from the head and stops at the first live one.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.