Fixed-TTL Session Token Manager
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Implement a session token service where every issued or refreshed token stays valid for a constant lifespan time_to_live (measured in seconds). Whenever a token is created or successfully refreshed at timestamp current_time, its expiration deadline becomes current_time + time_to_live.
Liveness uses a strict cutoff: at timestamp current_time, a token counts as active only while deadline > current_time. The instant the clock reaches deadline (current_time >= deadline), the token is treated as expired.
Write authentication_manager(time_to_live, operations, arguments) -> List[Optional[int]] (backed by an AuthenticationManager class) to process a batch of chronological operations in lockstep:
"AuthenticationManager"with[ttl]: initializes a fresh manager with lifespanttland appendsNoneto the output list."generate"with[token_id, current_time]: issuestoken_idwith deadlinecurrent_time + ttl. Iftoken_idis already present (active or expired), its deadline is replaced withcurrent_time + ttl. AppendsNone."renew"with[token_id, current_time]: iftoken_idexists and is still active atcurrent_time(deadline > current_time), updates its deadline tocurrent_time + ttl; iftoken_idhas never been issued or has already expired, does nothing. AppendsNone."countUnexpiredTokens"(or"count_unexpired_tokens") with[current_time]: appends the number of currently active tokens atcurrent_time.
def authentication_manager(
time_to_live: int,
operations: List[str],
arguments: List[List[object]],
) -> List[Optional[int]]:
pass
Examples
Example 1
Input:
time_to_live = 4
operations = [
"AuthenticationManager", "renew", "generate", "countUnexpiredTokens",
"generate", "renew", "renew", "countUnexpiredTokens", "countUnexpiredTokens"
]
arguments = [
[4], ["sess1", 1], ["sess1", 2], [5],
["sess2", 5], ["sess1", 6], ["sess2", 7], [8], [11]
]
Output:
[None, None, None, 1, None, None, None, 1, 0]
Walk-through:
- Initialize with ttl = 4 (None).
- At t = 1, "sess1" has not been issued yet, so renew("sess1", 1) does nothing (None).
- At t = 2, generate("sess1", 2) sets "sess1"'s deadline to 2 + 4 = 6 (None).
- At t = 5, "sess1" is active (6 > 5), so countUnexpiredTokens(5) returns 1.
- At t = 5, generate("sess2", 5) sets "sess2"'s deadline to 5 + 4 = 9 (None).
- At t = 6, "sess1" hits its exact deadline (6 is not greater than 6), so renew("sess1", 6) is ignored (None).
- At t = 7, "sess2" is still active (9 > 7), so renew("sess2", 7) pushes its deadline to 7 + 4 = 11 (None).
- At t = 8, only "sess2" remains active (11 > 8), returning 1. At t = 11, "sess2" has expired (11 is not greater than 11), returning 0.
Example 2
Input:
time_to_live = 6
operations = [
"AuthenticationManager", "generate", "generate",
"countUnexpiredTokens", "generate", "countUnexpiredTokens"
]
arguments = [
[6], ["api9", 3], ["web4", 4],
[8], ["api9", 9], [10]
]
Output:
[None, None, None, 2, None, 1]
Walk-through:
- Initialize with ttl = 6 (None).
- "api9" is issued at t = 3 (deadline 9) and "web4" is issued at t = 4 (deadline 10).
- At t = 8, both "api9" (9 > 8) and "web4" (10 > 8) are active, so the count is 2.
- At t = 9, generate("api9", 9) re-issues "api9" with a fresh deadline of 9 + 6 = 15.
- At t = 10, "web4" has just expired (10 is not greater than 10) while "api9" stays active until 15, so the count is 1.
Constraints
1 <= time_to_live <= 10^81 <= current_time <= 10^81 <= len(token_id) <= 20; eachtoken_idcontains only lowercase English letters ('a'–'z') and digits ('0'–'9').- Timestamp values passed across the operation sequence are monotonically non-decreasing.
1 <= len(operations) == len(arguments) <= 5 * 10^4
Step-by-step walkthrough
Understand the token lifecycle and strict expiry rule
We need an
AuthenticationManagerwhere every issued or refreshed token stays active for a constant time-to-live (TTL) window:generate(token_id, current_time): Issuestoken_id(or replaces its previous entry, active or expired) withexpiry_time = current_time + time_to_live.renew(token_id, current_time): Updatesexpiry_time = current_time + time_to_liveonly whentoken_idis present and currently active; otherwise leaves the state untouched.count_unexpired_tokens(current_time): Returns how many tokens remain active atcurrent_time.
Watch the exact cutoff carefully: a token stays active only while
expiry_time > current_time. The momentcurrent_time == expiry_time, that token is already expired:generate("sess1", current_time=2) with TTL=4 -> expiry_time = 6 time: 2 ---- 3 ---- 4 ---- 5 ---- 6 ---- 7 status: [ active (> t) ] X expired (6 is NOT > 6)The test harness invokes
authentication_manager(time_to_live, operations, arguments), stepping through method names and argument lists in parallel, appendingNonefor constructor/generate/renewcalls and the active count for count queries. (Both"countUnexpiredTokens"and"count_unexpired_tokens"are accepted.)Why scanning a plain dictionary is too slow
A simple first implementation stores
{token_id: expiry_time}in a regulardict:generateandrenewdo a singleO(1)lookup and update.count_unexpired_tokensloops through every stored token and counts how many satisfyexpiry_time > current_time.
What happens if
TTL = 10^8and we receive25,000generatecalls followed by25,000count_unexpired_tokenscalls? None of the tokens expire yet, so every single count query scans all25,000live tokens — roughly6.25 * 10^8loop iterations in Python, which times out. We needcount_unexpired_tokensto avoid re-scanning live tokens!Key idea: monotonic timestamps keep an OrderedDict sorted
Look at the two guarantees in the constraints:
current_timenever moves backward from one call to the next (t_1 <= t_2 <= ...).time_to_liveis constant across all tokens.
Therefore, every newly computed
current_time + time_to_liveis greater than or equal to every expiry timestamp computed earlier! If we store tokens in Python'scollections.OrderedDict(a dictionary backed by a doubly linked list that preserves insertion order and moves any existing key to the back inO(1)time via.move_to_end(key)), our map stays sorted from earliest expiry at the front to latest expiry at the back:TTL = 4: 1. generate("a", 1) -> OrderedDict: [ ("a", 5) ] 2. generate("b", 2) -> OrderedDict: [ ("a", 5), ("b", 6) ] 3. renew("a", 3) -> update "a" to 7 AND move_to_end("a"): OrderedDict: [ ("b", 6), ("a", 7) ] ^ front (earliest expiry!)Because entries stay sorted by ascending
expiry_time, all expired tokens always sit contiguously at the front ofOrderedDict:- Before any operation at
current_time, we pop tokens from the front whileoldest_expiry <= current_time. The moment the front token hasoldest_expiry > current_time, we stop immediately because every token behind it expires even later! - After that cleanup, every remaining entry in
OrderedDictis guaranteed to be active, socount_unexpired_tokensis simplylen(self.expiry_by_token)inO(1)time, andrenewonly needsif token_id in self.expiry_by_token:.
Why is front eviction fast overall? Each
generatecall adds at most1entry toOrderedDict(whilerenewandcountadd0), and each entry can be deleted at most once. AcrossNtotal calls, thewhileloop deletes at mostNentries in total — amortizedO(1)time per call!Implement AuthenticationManager with front eviction
One Python
OrderedDictdetail is critical: assigningself.expiry_by_token[token_id] = new_expiryto a key that already exists leaves that key in its old middle/front slot! Always follow the assignment withself.expiry_by_token.move_to_end(token_id)so the updated token moves to the back where its new, larger expiry belongs.from collections import OrderedDict class AuthenticationManager: def __init__(self, time_to_live: int): self.time_to_live = time_to_live # expiry_by_token: OrderedDict of {token_id: expiry_time}, e.g. {"t1": 7, "t2": 15}. # Because current_time is non-decreasing and time_to_live is constant, moving # every written token to the back keeps entries sorted by ascending expiry_time. self.expiry_by_token: OrderedDict[str, int] = OrderedDict() def _evict_expired(self, current_time: int) -> None: # Expired tokens (expiry_time <= current_time) always sit at the front. while self.expiry_by_token: oldest_token = next(iter(self.expiry_by_token)) if self.expiry_by_token[oldest_token] > current_time: # Front token is still strictly unexpired, so every later token is too. break del self.expiry_by_token[oldest_token] def generate(self, token_id: str, current_time: int) -> None: self._evict_expired(current_time) self.expiry_by_token[token_id] = current_time + self.time_to_live # Updating an existing key keeps its old position unless we explicitly move it to the back. self.expiry_by_token.move_to_end(token_id) def renew(self, token_id: str, current_time: int) -> None: self._evict_expired(current_time) # After _evict_expired, any token still in expiry_by_token has expiry_time > current_time. if token_id in self.expiry_by_token: self.expiry_by_token[token_id] = current_time + self.time_to_live self.expiry_by_token.move_to_end(token_id) def count_unexpired_tokens(self, current_time: int) -> int: self._evict_expired(current_time) return len(self.expiry_by_token)Write the operation-replay wrapper
The wrapper steps through
operationsandargumentsin lockstep usingzip(...), instantiatingAuthenticationManagerwhen"AuthenticationManager"appears and collectingNoneor the integer token count for each step.from typing import List, Optional def authentication_manager(time_to_live: int, operations: List[str], arguments: List[List[object]]) -> List[Optional[int]]: manager = AuthenticationManager(time_to_live) results: List[Optional[int]] = [] # Replay each method call in order; mutating calls return None, count calls return an int. for operation, args in zip(operations, arguments): if operation == "AuthenticationManager": ttl = int(args[0]) if args else time_to_live manager = AuthenticationManager(ttl) results.append(None) elif operation == "generate": manager.generate(str(args[0]), int(args[1])) results.append(None) elif operation == "renew": manager.renew(str(args[0]), int(args[1])) results.append(None) elif operation in ("countUnexpiredTokens", "count_unexpired_tokens"): # Accept both camelCase (judge sample) and snake_case (class interface). results.append(manager.count_unexpired_tokens(int(args[0]))) else: raise ValueError(f"Unknown operation: {operation}") return resultsTrace Example 1 step by step
With
TTL = 4, here isexpiry_by_token(front to back) after every operation in Example 1:operation evicted first expiry_by_token (front->back) output ------------------------------ -------------- ---------------------------------- ------ AuthenticationManager(4) - [] None renew("sess1", 1) none [] ("sess1" missing) None generate("sess1", 2) none [("sess1", 6)] None countUnexpiredTokens(5) none (6 > 5) [("sess1", 6)] 1 generate("sess2", 5) none (6 > 5) [("sess1", 6), ("sess2", 9)] None renew("sess1", 6) "sess1" (6<=6) [("sess2", 9)] (evicted, ignored!) None renew("sess2", 7) none (9 > 7) [("sess2", 11)] None countUnexpiredTokens(8) none (11 > 8) [("sess2", 11)] 1 countUnexpiredTokens(11) "sess2"(11<=11) [] 0Notice how
renew("sess1", 6)first runs_evict_expired(6), which deletes"sess1"because6 > 6isFalse, so the renewal cleanly ignores"sess1"while leaving"sess2"intact. Including the constructor'sNoneat index0, the returned list is[None, None, None, 1, None, None, None, 1, 0].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import OrderedDict class AuthenticationManager: def __init__(self, time_to_live: int): self.time_to_live = time_to_live # expiry_by_token: OrderedDict of {token_id: expiry_time}, e.g. {"t1": 7, "t2": 15}. # Because current_time is non-decreasing and time_to_live is constant, moving # every written token to the back keeps entries sorted by ascending expiry_time. self.expiry_by_token: OrderedDict[str, int] = OrderedDict() def _evict_expired(self, current_time: int) -> None: # Expired tokens (expiry_time <= current_time) always sit at the front. while self.expiry_by_token: oldest_token = next(iter(self.expiry_by_token)) if self.expiry_by_token[oldest_token] > current_time: # Front token is still strictly unexpired, so every later token is too. break del self.expiry_by_token[oldest_token] def generate(self, token_id: str, current_time: int) -> None: self._evict_expired(current_time) self.expiry_by_token[token_id] = current_time + self.time_to_live # Updating an existing key keeps its old position unless we explicitly move it to the back. self.expiry_by_token.move_to_end(token_id) def renew(self, token_id: str, current_time: int) -> None: self._evict_expired(current_time) # After _evict_expired, any token still in expiry_by_token has expiry_time > current_time. if token_id in self.expiry_by_token: self.expiry_by_token[token_id] = current_time + self.time_to_live self.expiry_by_token.move_to_end(token_id) def count_unexpired_tokens(self, current_time: int) -> int: self._evict_expired(current_time) return len(self.expiry_by_token) def authentication_manager(time_to_live: int, operations: List[str], arguments: List[List[object]]) -> List[Optional[int]]: manager = AuthenticationManager(time_to_live) results: List[Optional[int]] = [] # Replay each method call in order; mutating calls return None, count calls return an int. for operation, args in zip(operations, arguments): if operation == "AuthenticationManager": ttl = int(args[0]) if args else time_to_live manager = AuthenticationManager(ttl) results.append(None) elif operation == "generate": manager.generate(str(args[0]), int(args[1])) results.append(None) elif operation == "renew": manager.renew(str(args[0]), int(args[1])) results.append(None) elif operation in ("countUnexpiredTokens", "count_unexpired_tokens"): # Accept both camelCase (judge sample) and snake_case (class interface). results.append(manager.count_unexpired_tokens(int(args[0]))) else: raise ValueError(f"Unknown operation: {operation}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a shelf of milk cartons at a café where every fresh or re-stamped carton gets an expiration label equal to current_time + TTL (where TTL, or time-to-live, is the fixed lifespan added on each write) and is placed at the back of the row. Because the clock only moves forward and TTL never changes, every newly placed or re-stamped carton expires at least as late as anything already on the shelf. That means expired cartons always collect right at the front edge: you can sweep off expired cartons from the front until you hit one still-fresh carton, then immediately read the remaining shelf count without inspecting any carton behind it!
A naive dictionary mapping token_id -> expiry_time handles generate and renew in O(1) time, but count_unexpired_tokens must scan every stored token to check expiry_time > current_time — costing O(N) per count (O(N^2) across N calls when TTL is large). On the other hand, a plain first-in, first-out queue cannot easily pull a renewed token out of the middle of the line.
Python's OrderedDict (a hash map linked into a doubly linked list so keys keep their insertion order and can jump to the back in O(1) time via .move_to_end()) gives us both instant lookup by token_id and sorted expiry order. Tracing part of Example 1 with TTL = 4:
generate("sess1", 2)->OrderedDictis[("sess1", 6)].generate("sess2", 5)->[("sess1", 6), ("sess2", 9)].renew("sess1", 6)-> front"sess1"has6 <= 6(expired!), so_evict_expiredremoves it and the renewal is ignored ->[("sess2", 9)].renew("sess2", 7)->"sess2"is active (9 > 7), so update"sess2"to7 + 4 = 11and callmove_to_end("sess2")->[("sess2", 11)].count_unexpired_tokens(8)-> front"sess2"has11 > 8(active), returninglen(...) = 1.
Complexity
- Time: Amortized O(1) per operation, O(N) total across N operations. Amortized O(1) means that although a single call may occasionally pop many expired tokens at once, the average cost per operation over the whole sequence is constant. Hash lookups, updates,
move_to_end, andlenonOrderedDicteach takeO(1)time; across allNcalls, at mostNtokens are ever inserted bygenerate, and each inserted token is deleted by_evict_expiredat most once. - Space: O(U), where
U <= Nis the number of currently active tokens. Because every method evicts expired entries first, dead tokens never accumulate in memory after a call finishes.
Edge cases
- Exact expiration boundary (
current_time == expiry_time): A token stays active only whileexpiry_time > current_time. Atcurrent_time == expiry_time,_evict_expiredremoves it socount_unexpired_tokensexcludes it andrenewignores it (as seen in Example 1 whenrenew("sess1", 6)is ignored). renewon a non-existent token: Ignored without inserting anything intoOrderedDict.generateoverwriting an existing token: Whether the old token is still active or already expired (likegenerate("api9", 9)in Example 2),generatesetsexpiry_time = current_time + TTLand moves it to the back.- Older token renewed past a newer token: Calling
move_to_end(token_id)ensures the renewed token jumps behind newer tokens with smaller expiry times, preserving sorted order. - Chained renewals: Each valid
renewsetscurrent_time + TTL(replacing, not adding to, the previousexpiry_time). - Multiple tokens at the exact same
current_time: All share the sameexpiry_timeand are evicted together whencurrent_timereaches that timestamp.
Common mistakes
- Using
>=instead of>for liveness: Keeping tokens withexpiry_time >= current_timewrongly treats a token as active at the exact second it expires. - Forgetting
move_to_end(token_id)when updating an existing key: In Python'sOrderedDict(and standarddict), overwriting an existing key leaves it in its old position! If an older token is renewed past a newer token ("b"expiring at7) to8while staying at the front,_evict_expired(7)stops at"a"(8 > 7) and fails to evict expired"b"(7 <= 7) hiding behind it! - Allowing
renewto create missing tokens or revive expired ones: Onlygeneratecan create or revive a token. - Scanning all dictionary entries on every
count_unexpired_tokens: Degrades toO(N^2)when thousands of long-lived tokens are counted repeatedly.
Alternative approaches
- Hash map + lazy FIFO queue (
dequeof(expiry_time, token_id)): Keep a plaindict{token_id: current_expiry}alongside adequewhere everygenerateandrenewappends(new_expiry, token_id)without removing the old queue entry (lazy deletion). During eviction, pop pairs from the front whilepair_expiry <= current_time, and only deletetoken_idfrom thedictifdict.get(token_id) == pair_expiry(ignoring stale queue pairs from earlier renewals). Also amortizedO(1)time, using up toO(N)queue slots instead ofO(U).
Follow-up questions
- What changes are needed if requests arrive out of chronological order from separate application nodes? Out-of-order timestamps break
OrderedDictsorted order AND break causal ordering: ifrenew("sess1", 8)arrives before a delayedrenew("sess1", 5)(for"sess1"originally expiring at6), discardingrenew("sess1", 8)immediately would be wrong oncerenew("sess1", 5)arrives and extends"sess1"to9, and evicting at time10would destroy state still needed by a latecount(4). In production, avoid clock skew (mismatched clocks across machines) by assigning timestamps at a single authoritative token store (such as Redis with native per-keyTTL), or if client event-time semantics are required, buffer incoming events in a min-heap and process them in chronological order behind a watermark (max_seen_time - max_allowed_lateness). - Can active token queries guarantee worst-case O(1) or O(log U) latency instead of only amortized O(1)? Our
OrderedDictdesign achieves amortized O(1) time becauselen(self.expiry_by_token)isO(1)after popping newly expired front tokens, yet one call after a quiet period could still evictKexpired tokens at once (O(K)worst-case for that single call). To enforce a hard per-call latency bound, cap eviction work per call (or run a background sweeper) while maintaining an order-statistic tree (a balanced binary search tree storing subtree sizes) of active deadlines to insert, delete onrenew/generate, and count entries strictly abovecurrent_timein deterministicO(log U)worst-case time without waiting on bulk deletions. - How would you make this token store safe under concurrent reads and writes from many threads? Wrap every public method (
generate,renew,count_unexpired_tokens) with a mutex lock (threading.Lock, a synchronization primitive allowing only one thread inside a critical section at a time) viawith self.lock:. Evencount_unexpired_tokensmutatesOrderedDictduring_evict_expired, and Python's Global Interpreter Lock (GIL) does not make multi-step check-then-update sequences inrenewatomic. If single-lock contention becomes a bottleneck across many CPU cores, apply lock striping (sharding): partition tokens acrossSindependentAuthenticationManagershards byhash(token_id) % S, each protected by its own lock sogenerateandrenewexecute in parallel across shards whilecount_unexpired_tokenssums theSshard counts.
Follow-up questions
- What changes are needed if requests arrive out of chronological order from separate application nodes?
- Can active token queries guarantee worst-case O(1) or O(log U) latency instead of only amortized O(1)?
- How would you make this token store safe under concurrent reads and writes from many threads?
Similar questions
- Eliminate Adjacent Identical Letters
- Total Revenue from Highest-Stock VM Allocation
- Active Employees With Unbroken Badge Renewals
- Bounded-Range Index Triplet Count
- Minimum Substitutions to Break Character Triples
- Counting Price-Matched Seat Trios
More IBM interview questions
- Report Accounts With High Mean Resource Utilization Medium
- Pythagorean Triple Nodes in a Tree Medium
- One-Way Video Behavioral Assessment: Six Timed Engineering Prompts Medium Pro
- Active Employees With Unbroken Badge Renewals Medium Pro
- Bounded-Range Index Triplet Count Medium Pro
- Counting Price-Matched Seat Trios Medium Pro
- Consistent Sensor Trio Count Medium Pro
- Harden an In-Memory Event Ticket Reservation Service Medium Pro
- End-to-End B2B Lead Prioritization and Scoring System Easy Pro
- Measuring Trial-to-Paid Conversion Probability Easy Pro