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 lifespan ttl and appends None to the output list.
  • "generate" with [token_id, current_time]: issues token_id with deadline current_time + ttl. If token_id is already present (active or expired), its deadline is replaced with current_time + ttl. Appends None.
  • "renew" with [token_id, current_time]: if token_id exists and is still active at current_time (deadline > current_time), updates its deadline to current_time + ttl; if token_id has never been issued or has already expired, does nothing. Appends None.
  • "countUnexpiredTokens" (or "count_unexpired_tokens") with [current_time]: appends the number of currently active tokens at current_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^8
  • 1 <= current_time <= 10^8
  • 1 <= len(token_id) <= 20; each token_id contains 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

  1. Understand the token lifecycle and strict expiry rule

    We need an AuthenticationManager where every issued or refreshed token stays active for a constant time-to-live (TTL) window:

    • generate(token_id, current_time): Issues token_id (or replaces its previous entry, active or expired) with expiry_time = current_time + time_to_live.
    • renew(token_id, current_time): Updates expiry_time = current_time + time_to_live only when token_id is present and currently active; otherwise leaves the state untouched.
    • count_unexpired_tokens(current_time): Returns how many tokens remain active at current_time.

    Watch the exact cutoff carefully: a token stays active only while expiry_time > current_time. The moment current_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, appending None for constructor/generate/renew calls and the active count for count queries. (Both "countUnexpiredTokens" and "count_unexpired_tokens" are accepted.)

  2. Why scanning a plain dictionary is too slow

    A simple first implementation stores {token_id: expiry_time} in a regular dict:

    • generate and renew do a single O(1) lookup and update.
    • count_unexpired_tokens loops through every stored token and counts how many satisfy expiry_time > current_time.

    What happens if TTL = 10^8 and we receive 25,000 generate calls followed by 25,000 count_unexpired_tokens calls? None of the tokens expire yet, so every single count query scans all 25,000 live tokens — roughly 6.25 * 10^8 loop iterations in Python, which times out. We need count_unexpired_tokens to avoid re-scanning live tokens!

  3. Key idea: monotonic timestamps keep an OrderedDict sorted

    Look at the two guarantees in the constraints:

    1. current_time never moves backward from one call to the next (t_1 <= t_2 <= ...).
    2. time_to_live is constant across all tokens.

    Therefore, every newly computed current_time + time_to_live is greater than or equal to every expiry timestamp computed earlier! If we store tokens in Python's collections.OrderedDict (a dictionary backed by a doubly linked list that preserves insertion order and moves any existing key to the back in O(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 of OrderedDict:

    • Before any operation at current_time, we pop tokens from the front while oldest_expiry <= current_time. The moment the front token has oldest_expiry > current_time, we stop immediately because every token behind it expires even later!
    • After that cleanup, every remaining entry in OrderedDict is guaranteed to be active, so count_unexpired_tokens is simply len(self.expiry_by_token) in O(1) time, and renew only needs if token_id in self.expiry_by_token:.

    Why is front eviction fast overall? Each generate call adds at most 1 entry to OrderedDict (while renew and count add 0), and each entry can be deleted at most once. Across N total calls, the while loop deletes at most N entries in total — amortized O(1) time per call!

  4. Implement AuthenticationManager with front eviction

    One Python OrderedDict detail is critical: assigning self.expiry_by_token[token_id] = new_expiry to a key that already exists leaves that key in its old middle/front slot! Always follow the assignment with self.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)
    
  5. Write the operation-replay wrapper

    The wrapper steps through operations and arguments in lockstep using zip(...), instantiating AuthenticationManager when "AuthenticationManager" appears and collecting None or 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 results
    
  6. Trace Example 1 step by step

    With TTL = 4, here is expiry_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) []                                  0
    

    Notice how renew("sess1", 6) first runs _evict_expired(6), which deletes "sess1" because 6 > 6 is False, so the renewal cleanly ignores "sess1" while leaving "sess2" intact. Including the constructor's None at index 0, the returned list is [None, None, None, 1, None, None, None, 1, 0].

  7. 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:

  1. generate("sess1", 2) -> OrderedDict is [("sess1", 6)].
  2. generate("sess2", 5) -> [("sess1", 6), ("sess2", 9)].
  3. renew("sess1", 6) -> front "sess1" has 6 <= 6 (expired!), so _evict_expired removes it and the renewal is ignored -> [("sess2", 9)].
  4. renew("sess2", 7) -> "sess2" is active (9 > 7), so update "sess2" to 7 + 4 = 11 and call move_to_end("sess2") -> [("sess2", 11)].
  5. count_unexpired_tokens(8) -> front "sess2" has 11 > 8 (active), returning len(...) = 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, and len on OrderedDict each take O(1) time; across all N calls, at most N tokens are ever inserted by generate, and each inserted token is deleted by _evict_expired at most once.
  • Space: O(U), where U <= N is 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 while expiry_time > current_time. At current_time == expiry_time, _evict_expired removes it so count_unexpired_tokens excludes it and renew ignores it (as seen in Example 1 when renew("sess1", 6) is ignored).
  • renew on a non-existent token: Ignored without inserting anything into OrderedDict.
  • generate overwriting an existing token: Whether the old token is still active or already expired (like generate("api9", 9) in Example 2), generate sets expiry_time = current_time + TTL and 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 renew sets current_time + TTL (replacing, not adding to, the previous expiry_time).
  • Multiple tokens at the exact same current_time: All share the same expiry_time and are evicted together when current_time reaches that timestamp.

Common mistakes

  • Using >= instead of > for liveness: Keeping tokens with expiry_time >= current_time wrongly treats a token as active at the exact second it expires.
  • Forgetting move_to_end(token_id) when updating an existing key: In Python's OrderedDict (and standard dict), overwriting an existing key leaves it in its old position! If an older token is renewed past a newer token ("b" expiring at 7) to 8 while staying at the front, _evict_expired(7) stops at "a" (8 > 7) and fails to evict expired "b" (7 <= 7) hiding behind it!
  • Allowing renew to create missing tokens or revive expired ones: Only generate can create or revive a token.
  • Scanning all dictionary entries on every count_unexpired_tokens: Degrades to O(N^2) when thousands of long-lived tokens are counted repeatedly.

Alternative approaches

  • Hash map + lazy FIFO queue (deque of (expiry_time, token_id)): Keep a plain dict {token_id: current_expiry} alongside a deque where every generate and renew appends (new_expiry, token_id) without removing the old queue entry (lazy deletion). During eviction, pop pairs from the front while pair_expiry <= current_time, and only delete token_id from the dict if dict.get(token_id) == pair_expiry (ignoring stale queue pairs from earlier renewals). Also amortized O(1) time, using up to O(N) queue slots instead of O(U).

Follow-up questions

  • What changes are needed if requests arrive out of chronological order from separate application nodes? Out-of-order timestamps break OrderedDict sorted order AND break causal ordering: if renew("sess1", 8) arrives before a delayed renew("sess1", 5) (for "sess1" originally expiring at 6), discarding renew("sess1", 8) immediately would be wrong once renew("sess1", 5) arrives and extends "sess1" to 9, and evicting at time 10 would destroy state still needed by a late count(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-key TTL), 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 OrderedDict design achieves amortized O(1) time because len(self.expiry_by_token) is O(1) after popping newly expired front tokens, yet one call after a quiet period could still evict K expired 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 on renew/generate, and count entries strictly above current_time in deterministic O(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) via with self.lock:. Even count_unexpired_tokens mutates OrderedDict during _evict_expired, and Python's Global Interpreter Lock (GIL) does not make multi-step check-then-update sequences in renew atomic. If single-lock contention becomes a bottleneck across many CPU cores, apply lock striping (sharding): partition tokens across S independent AuthenticationManager shards by hash(token_id) % S, each protected by its own lock so generate and renew execute in parallel across shards while count_unexpired_tokens sums the S shard counts.

Follow-up questions

Similar questions

More IBM interview questions

All 27 IBM questions →