Paginated Chat Transcript Loading and Token-Budget Eviction
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement two core components of an LLM chat backend's transcript manager:
- Part 1 — Cursor-Based Transcript Fetching (
iter_historyandload_history): Stream and materialize a conversation stored behind a paginatedfetch_page(cursor)callback. - Part 2 — Token-Budget Sliding Buffer (
History): Maintain an in-memory prompt buffer that automatically evicts the oldest non-system turns whenever appending a new turn pushes the running token total pasttoken_limit.
Use the following types, exceptions, and signatures:
from typing import Callable, Iterator, List, Optional, Tuple
from dataclasses import dataclass
import time
@dataclass(frozen=True)
class Message:
id: str
role: str
text: str
tokens: int
FetchPage = Callable[[Optional[str]], Tuple[List[Message], Optional[str]]]
class TransientFetchError(Exception):
"""Temporary upstream failure that should be retried with backoff."""
class RepeatedCursorError(Exception):
"""Upstream returned a cursor that was already seen earlier in the traversal."""
def iter_history(
fetch_page: FetchPage,
max_attempts: int = 3,
base_delay: float = 0.1,
sleep: Callable[[float], None] = time.sleep,
) -> Iterator[Message]: ...
def load_history(
fetch_page: FetchPage,
newest_first: bool = False,
max_attempts: int = 3,
base_delay: float = 0.1,
sleep: Callable[[float], None] = time.sleep,
) -> List[Message]: ...
class History:
total_tokens: int
def __init__(self, token_limit: int, system_message: Optional[Message] = None): ...
def add(self, message: Message) -> List[Message]: ...
def messages(self) -> List[Message]: ...
def __len__(self) -> int: ...
Detailed Rules
Part 1: iter_history and load_history
- Cursor progression and termination: Request the first page with
cursor=None. Each call returns(page_messages, next_cursor). Continue requestingnext_cursoruntilfetch_pagereturnsnext_cursor=None, which marks the final page. An emptypage_messageslist paired with a non-Nonenext_cursordoes not terminate pagination. - Lazy streaming (
iter_history): Yield messages one at a time in the order returned byfetch_page. Do not fetch the first page until iteration begins, and do not fetch the next page until the caller consumes every item from the current page. - Cycle protection: Track every non-
Nonecursor returned during a traversal. Iffetch_pagereturns a cursor that has already appeared earlier (either back-to-back like"c1" -> "c1"or via a multi-page loop like"p1" -> "p2" -> "p1"), raiseRepeatedCursorErrorimmediately without requesting that cursor again. - Retry with exponential backoff: Validate
max_attempts >= 1andbase_delay >= 0, raisingValueErrorotherwise. Wheneverfetch_page(cursor)raisesTransientFetchError, retry that same cursor up tomax_attemptstotal calls for that page. After failed attemptk(1 <= k < max_attempts), callsleep(base_delay * (2 ** (k - 1)))(base_delay,2 * base_delay,4 * base_delay, ...). If attemptmax_attemptsstill raisesTransientFetchError, propagate it without callingsleepagain. Do not retry any other exception type. - Eager chronological loading (
load_history): Collect the entire conversation into alist[Message]ordered oldest-to-newest. Whennewest_first=False, the source already serves pages and intra-page items oldest-first. Whennewest_first=True, the source serves pages newest-first and items within each page newest-first, so reverse the collected stream before returning.
Part 2: History
- Initialization and validation: Raise
ValueErroriftoken_limit <= 0. Ifsystem_messageis provided, raiseValueErrorifsystem_message.tokens < 0orsystem_message.tokens > token_limit. Initializeself.total_tokenstosystem_message.tokensif present, or0otherwise. - Pinned system prompt: When
system_messageis set, it stays permanently at index0ofmessages(), is never evicted byadd, and is not counted bylen(history), though its tokens always count towardself.total_tokens. - Adding turns and evicting (
add): RaiseValueErrorifmessage.tokens < 0. Appendmessageas the newest turn, then repeatedly evict the oldest retained non-system message whileself.total_tokens > token_limit(a total exactly equal totoken_limitfits without eviction). Return the evictedMessageobjects in eviction order (oldest first). Ifmessagealone exceeds the remaining non-system budget (token_limit - system_tokens), all prior non-system messages andmessageitself are evicted and returned. - Inspection (
messagesand__len__):messages()returns a fresh list containingsystem_message(if any) followed by all retained non-system messages from oldest to newest.len(history)returns the number of retained non-system messages.
Examples
Example 1
Suppose fetch_page serves three pages for u1 (5 tokens), a1 (4 tokens), and u2 (6 tokens):
cursor=Nonereturns([u1, a1], "cur_1")cursor="cur_1"returns([], "cur_2")(an empty intermediate page)cursor="cur_2"raisesTransientFetchErroron its first call, then returns([u2], None)on its second call
Input:
load_history(fetch_page, max_attempts=3, base_delay=0.05, sleep=recorder)
Output:
[u1, a1, u2]
Walk-through: iter_history requests None and yields u1, a1. Seeing "cur_1", it fetches the empty middle page and keeps going because next_cursor="cur_2" is non-None. On "cur_2", the first attempt fails with TransientFetchError, so recorder records one backoff delay of 0.05 seconds before the retry succeeds with ([u2], None) and ends pagination.
Example 2
Track five turns arriving into History(token_limit=12) with no system message: t1 (5 tokens), t2 (4 tokens), t3 (3 tokens), t4 (4 tokens), and t5 (6 tokens).
Input:
history = History(token_limit=12)
d1 = history.add(t1) # 5 tokens
d2 = history.add(t2) # 4 tokens
d3 = history.add(t3) # 3 tokens
d4 = history.add(t4) # 4 tokens
d5 = history.add(t5) # 6 tokens
Output:
d1 == []
d2 == []
d3 == []
d4 == [t1]
d5 == [t2, t3]
history.messages() == [t4, t5]
history.total_tokens == 10
len(history) == 2
Walk-through: After t1, t2, and t3, the total reaches 5 + 4 + 3 = 12, which equals token_limit and keeps all three turns. Appending t4 (4) raises the sum to 16 > 12, evicting t1 (5) to reach 11 <= 12. Appending t5 (6) raises the sum to 17 > 12; popping t2 (4) leaves 13 > 12, so t3 (3) is also popped, bringing total_tokens to 10 <= 12 with [t4, t5] retained.
Example 3
Pin sys_msg (3 tokens) inside History(token_limit=10, system_message=sys_msg) and add m1 (4 tokens), m2 (4 tokens), and an oversized turn huge (9 tokens).
Input:
history = History(token_limit=10, system_message=sys_msg)
e1 = history.add(m1) # 4 tokens
e2 = history.add(m2) # 4 tokens
e3 = history.add(huge) # 9 tokens
Output:
e1 == []
e2 == [m1]
e3 == [m2, huge]
history.messages() == [sys_msg]
history.total_tokens == 3
len(history) == 0
Walk-through: sys_msg permanently reserves 3 of the 10 tokens, leaving 7 tokens for conversation turns. m1 (4) fits at 7 <= 10. Adding m2 (4) reaches 11 > 10 and evicts m1, leaving [sys_msg, m2] at 7 tokens. Adding huge (9) reaches 16 > 10, evicting m2 (12 > 10) and then huge itself (3 <= 10), leaving sys_msg intact.
Constraints
token_limit >= 1for validHistoryconfigurations; raiseValueErrorwhentoken_limit <= 0.- Every valid
Messagehastokens >= 0(tokens == 0is allowed); raiseValueErrorfor negativetokensor whensystem_message.tokens > token_limit. max_attempts >= 1andbase_delay >= 0.0; raiseValueErrorotherwise.History.addmay be invoked3 * 10^5or more times sequentially and must run in amortizedO(1)time per message (len(history)inO(1)time).
Step-by-step walkthrough
Restate the problem and pin down the contract
We are building two connected pieces of a conversation agent's memory layer:
- Part 1 — Pagination (
iter_historyandload_history): Given a functionfetch_page(cursor)that takes an opaque cursor (a bookmark token handed back by the server to tell it where the next page begins) and returns(page_messages, next_cursor), assemble the conversation in chronological order (oldest message first). The first call passescursor=None, andnext_cursor=Nonemarks the final page. - Part 2 — Token-limit compaction (
History): Maintain a live conversation buffer with a positivetoken_limit. Everyadd(message)appends the newest message and evicts the oldest messages until the total token count is<= token_limit, returning any evicted messages in oldest-first order.
Because real-world specs leave room for clarification, state the concrete rules our contract enforces: - By default, pages arrive oldest-first and messages within each page are oldest-first;
newest_first=Truehandles an API whose stream is newest-first end-to-end. - A total equal totoken_limitfits (total_tokens <= token_limit). -TransientFetchError(such as a network timeout or HTTP 503) is retried per page up tomax_attemptstotal calls using exponential backoff (doubling the wait time after each failure:base_delay,2 * base_delay,4 * base_delay, ...). Non-transient errors (likeValueError) fail immediately. - An optionalsystem_messageis pinned at the front: it counts towardtoken_limitand is never evicted. - If a single new message is larger than the remaining budget, all older non-system messages and the oversized message itself are evicted and returned byadd.- Part 1 — Pagination (
Why the obvious first drafts break or crawl
In Part 1, beginners commonly write a loop that checks
if not page: breakorwhile cursor::Bug 1: while cursor: ... -> cursor starts at None, so page 1 is NEVER fetched! Bug 2: if not page: break -> stops early when a page is empty (e.g., deleted messages filtered out server-side) even though next_cursor = "c2"! Bug 3: no cursor tracking -> if a buggy server returns A -> B -> A, the client loops forever! Bug 4: prepending page[::-1] + msgs -> copies all loaded messages on every page: O(N * P) instead of O(N).In Part 2, the obvious compaction loop calls
sum(m.tokens for m in msgs)andmsgs.pop(0)after everyadd: -sum(...)re-reads allNkept messages on every turn:O(N). -list.pop(0)on a Pythonlistshifts every remaining element one slot to the left in memory: alsoO(N).Running an
O(N)step acrossNmessages costsO(N^2)total time. On 300,000 messages with a 150,000-token window,O(N^2)re-summing takes minutes andlist.pop(0)takes seconds, whereas maintaining a running integer sum and a double-ended queue finishes in a few tens of milliseconds.Retry transient page failures with exponential backoff
Isolate retry logic into a small helper
fetch_with_retrythat fetches one page. Retrying at the single-page level is much cleaner than restartingload_historyfrom scratch: if page 47 times out, pages 1 through 46 stay intact.We also accept
sleepas an injected function parameter (defaulting totime.sleep) so unit tests can pass a fake recorder and verify exact backoff delays in microseconds without actually sleeping.def fetch_with_retry(fetch_page: FetchPage, cursor: Optional[str], max_attempts: int, base_delay: float, sleep: Callable[[float], None]) -> Tuple[List[Message], Optional[str]]: """Call fetch_page(cursor), retrying TransientFetchError with exponential backoff.""" if max_attempts < 1: raise ValueError("max_attempts must be at least 1") if base_delay < 0: raise ValueError("base_delay cannot be negative") # attempt counts 1-indexed calls for this single page (1, 2, ..., max_attempts). attempt = 1 while True: try: return fetch_page(cursor) except TransientFetchError: # Stop retrying once we have used all allowed attempts so we do not sleep in vain. if attempt >= max_attempts: raise # Exponential backoff: base_delay, 2 * base_delay, 4 * base_delay, ... delay = base_delay * (2 ** (attempt - 1)) sleep(delay) attempt += 1Notice
if attempt >= max_attempts: raiseruns beforesleep(delay): ifmax_attempts = 3and all 3 tries fail, we sleep only twice (0.1s,0.2s) and surface the 3rd exception immediately.Paginate lazily with a generator, and detect cursor cycles
Write the core pagination loop as a Python generator (a function using
yieldthat produces items on demand and pauses between them). That gives us lazy loading for free:iter_historyfetches the next page only when the caller reads past the end of the current page, keeping memory at a single page if the caller stops early.Trace how
cursorandseen_cursorsadvance on Example 1's stream (including an empty middle page) versus a broken cyclic stream:Normal stream (Example 1, with an empty middle page): call 1: cursor=None -> ([u1, a1], "cur_1") yield u1, a1; seen={"cur_1"} call 2: cursor="cur_1" -> ([], "cur_2") empty page, NOT the end! seen={"cur_1", "cur_2"} call 3: cursor="cur_2" -> ([u2], None) yield u2; next_cursor is None -> STOP. Broken cyclic stream: call 1: cursor=None -> ([u1], "p1") seen={"p1"} call 2: cursor="p1" -> ([a1], "p2") seen={"p1", "p2"} call 3: cursor="p2" -> ([u2], "p1") "p1" is already in seen -> raise RepeatedCursorError!Look closely at the order of the two checks at the bottom of the loop: 1. Check
if next_cursor is None: returnfirst, becauseNonemeans "stream finished", not "go back to page 1". 2. Then checkif next_cursor in seen_cursors:, which catches both direct self-loops ("c1" -> "c1") and multi-page cycles ("p1" -> "p2" -> "p1").load_historyis the eager wrapper: it drainsiter_historyinto a list and, ifnewest_first=True, reverses the list once at the end inO(N)time.def iter_history(fetch_page: FetchPage, max_attempts: int = 3, base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> Iterator[Message]: """Lazily yield every message in the order the source serves them.""" # First page is always requested with cursor=None. cursor = None # seen_cursors: set of non-None cursor strings already returned, e.g. {"c1", "c2"}. seen_cursors = set() while True: page, next_cursor = fetch_with_retry(fetch_page, cursor, max_attempts, base_delay, sleep) for message in page: yield message # Check next_cursor is None FIRST: an empty page with a non-None cursor must keep going, # and None marks normal end-of-stream rather than a repeated cursor back to page 1. if next_cursor is None: return if next_cursor in seen_cursors: raise RepeatedCursorError(f"cursor {next_cursor!r} was returned twice") seen_cursors.add(next_cursor) cursor = next_cursor def load_history(fetch_page: FetchPage, newest_first: bool = False, max_attempts: int = 3, base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> List[Message]: """Eagerly load the whole conversation, oldest message first.""" messages = [] for message in iter_history(fetch_page, max_attempts, base_delay, sleep): messages.append(message) # Reverse once at the end in O(N) time instead of prepending each page in O(N * P) time. if newest_first: messages.reverse() return messagesCompact in amortized O(1) time with a running sum and a deque
Two simple data-structure choices eliminate all
O(N)work per message:- Running token counter (
self.total_tokens): Addmessage.tokenswhen appending, and subtractoldest.tokenswhen evicting. Checking whether we exceedtoken_limittakesO(1)time. - Double-ended queue (
collections.deque): Unlike a Pythonlist, a deque (pronounced "deck") stores elements in linked fixed-size blocks so bothappend(x)on the right andpopleft()on the left run inO(1)time with zero element shifting.
Pinned slot Sliding deque self._messages (oldest -> newest) +-----------------+ +----------+----------+ | sys_msg (3 tok) | + | m1:4 tok | m2:4 tok | total_tokens = 3 + 4 + 4 = 11 > 10 +-----------------+ +----------+----------+ (never popped) ^ ^ | popleft() | append(m2) in O(1) evicts m1:4 -> total_tokens = 7 <= 10Why is
addamortized O(1) (meaning the average cost per operation over any sequence ofNoperations is bounded by a constant, even if one call occasionally does more work)? Oneaddmight pop several small messages at once, takingO(k)time forkpops. However, every message can enterself._messagesonce and leaveself._messagesat most once. AcrossNcalls toadd, total appends areNand totalpopleftcalls are<= N, so total work isO(N)—O(1)amortized per message!Why can
self._messages.popleft()never crash on an empty deque? In__init__, we enforce0 <= system_message.tokens <= token_limit. Even if a huge message arrives and forces every item inself._messages(including the new message itself!) to be popped,self.total_tokensreturns tosystem_message.tokens(or0), which is<= token_limit, terminatingwhile self.total_tokens > self.token_limit:cleanly.- Running token counter (
Code the `History` class
Let's assemble
Historywith full input validation (token_limit <= 0, negativetokenson eithersystem_messageor added messages, andsystem_message.tokens > token_limit):class History: """Conversation history that keeps its token total at or below token_limit by dropping the oldest messages. An optional system message is always kept and counts toward the limit. """ def __init__(self, token_limit: int, system_message: Optional[Message] = None): if token_limit <= 0: raise ValueError("token_limit must be positive") if system_message is not None: if system_message.tokens < 0: raise ValueError("token counts cannot be negative") if system_message.tokens > token_limit: raise ValueError("the system message alone exceeds the token limit") self.token_limit = token_limit self.system_message = system_message # self._messages: deque of kept non-system Message objects, [oldest, ..., newest]. self._messages = deque() # Running sum of tokens across system_message (if any) plus all items in self._messages. self.total_tokens = 0 if system_message is not None: self.total_tokens = system_message.tokens def add(self, message: Message) -> List[Message]: """Append message, then drop the oldest messages until total_tokens <= token_limit.""" if message.tokens < 0: raise ValueError("token counts cannot be negative") # Phase 1: append the newest message on the right in O(1) and update the running sum. self._messages.append(message) self.total_tokens += message.tokens # dropped: evicted Message objects in eviction order [oldest_dropped, ...]. dropped = [] # Phase 2: use strict '>' because total_tokens == token_limit still fits. # Since system_message.tokens <= token_limit, popping all of self._messages (including # an oversized new message) brings total_tokens <= token_limit before the deque is empty. while self.total_tokens > self.token_limit: oldest = self._messages.popleft() self.total_tokens -= oldest.tokens dropped.append(oldest) return dropped def messages(self) -> List[Message]: """Return [system_message] (if present) followed by kept messages oldest first.""" result = [] if self.system_message is not None: result.append(self.system_message) result.extend(self._messages) return result def __len__(self) -> int: """Number of kept non-system messages.""" return len(self._messages)Trace normal compaction, oversized messages, and agent loop timing
Walk through Example 2 (
History(token_limit=12)) as turnst1:5, t2:4, t3:3, t4:4, t5:6arrive:call after append (total) evicted (oldest first) kept deque final total ------- ---------------------- ---------------------- ---------------- ----------- add(t1) [t1] (5) [] [t1] 5 add(t2) [t1, t2] (9) [] [t1, t2] 9 add(t3) [t1, t2, t3] (12) [] [t1, t2, t3] 12 (== limit fits!) add(t4) [t1, t2, t3, t4] (16) [t1] [t2, t3, t4] 11 add(t5) [t2, t3, t4, t5] (17) [t2, t3] [t4, t5] 10Now trace Example 3's oversized turn
huge:9added toHistory(token_limit=10, system_message=sys_msg:3)currently holding[m2:4](total_tokens = 7): 1. Appendhuge:9-> deque[m2, huge],total_tokens = 3 + 4 + 9 = 16 > 10. 2. Popm2:4->total_tokens = 12 > 10; pophuge:9->total_tokens = 3 <= 10. 3.add(huge)returns[m2, huge],history.messages()stays[sys_msg],len(history)is0, and subsequent turns that fit within the remaining7-token non-system budget can still be added normally.Where does compaction sit relative to LLM calls? Because
add()compacts eagerly on every insertion,history.messages()is guaranteed within budget before every model call:1. User sends turn -> history.add(user_msg) (compacts immediately) 2. Call LLM API -> send history.messages() (guaranteed <= token_limit) 3. Receive LLM reply -> history.add(assistant_msg) (compacts immediately)In production, set
token_limittomodel_context_window - max_output_tokens - tool_schema_tokens, not the raw context window, so the model always has room to generate its reply.Complete solution
from typing import Callable, Iterator, List, Optional, Tuple from collections import deque from dataclasses import dataclass import time @dataclass(frozen=True) class Message: id: str role: str # for example "user" or "assistant" text: str tokens: int # token count of this message FetchPage = Callable[[Optional[str]], Tuple[List[Message], Optional[str]]] class TransientFetchError(Exception): """A fetch failure worth retrying, such as a timeout or a 503.""" class RepeatedCursorError(Exception): """The source returned a cursor it had already returned, so the pages would loop forever.""" # ---------------------------------------------------------------- Part 1: pagination def fetch_with_retry(fetch_page: FetchPage, cursor: Optional[str], max_attempts: int, base_delay: float, sleep: Callable[[float], None]) -> Tuple[List[Message], Optional[str]]: """Call fetch_page(cursor), retrying TransientFetchError with exponential backoff.""" if max_attempts < 1: raise ValueError("max_attempts must be at least 1") if base_delay < 0: raise ValueError("base_delay cannot be negative") # attempt counts 1-indexed calls for this single page (1, 2, ..., max_attempts). attempt = 1 while True: try: return fetch_page(cursor) except TransientFetchError: # Stop retrying once we have used all allowed attempts so we do not sleep in vain. if attempt >= max_attempts: raise # Exponential backoff: base_delay, 2 * base_delay, 4 * base_delay, ... delay = base_delay * (2 ** (attempt - 1)) sleep(delay) attempt += 1 def iter_history(fetch_page: FetchPage, max_attempts: int = 3, base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> Iterator[Message]: """Lazily yield every message in the order the source serves them.""" # First page is always requested with cursor=None. cursor = None # seen_cursors: set of non-None cursor strings already returned, e.g. {"c1", "c2"}. seen_cursors = set() while True: page, next_cursor = fetch_with_retry(fetch_page, cursor, max_attempts, base_delay, sleep) for message in page: yield message # Check next_cursor is None FIRST: an empty page with a non-None cursor must keep going, # and None marks normal end-of-stream rather than a repeated cursor back to page 1. if next_cursor is None: return if next_cursor in seen_cursors: raise RepeatedCursorError(f"cursor {next_cursor!r} was returned twice") seen_cursors.add(next_cursor) cursor = next_cursor def load_history(fetch_page: FetchPage, newest_first: bool = False, max_attempts: int = 3, base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> List[Message]: """Eagerly load the whole conversation, oldest message first.""" messages = [] for message in iter_history(fetch_page, max_attempts, base_delay, sleep): messages.append(message) # Reverse once at the end in O(N) time instead of prepending each page in O(N * P) time. if newest_first: messages.reverse() return messages # ---------------------------------------------------------------- Part 2: compaction class History: """Conversation history that keeps its token total at or below token_limit by dropping the oldest messages. An optional system message is always kept and counts toward the limit. """ def __init__(self, token_limit: int, system_message: Optional[Message] = None): if token_limit <= 0: raise ValueError("token_limit must be positive") if system_message is not None: if system_message.tokens < 0: raise ValueError("token counts cannot be negative") if system_message.tokens > token_limit: raise ValueError("the system message alone exceeds the token limit") self.token_limit = token_limit self.system_message = system_message # self._messages: deque of kept non-system Message objects, [oldest, ..., newest]. self._messages = deque() # Running sum of tokens across system_message (if any) plus all items in self._messages. self.total_tokens = 0 if system_message is not None: self.total_tokens = system_message.tokens def add(self, message: Message) -> List[Message]: """Append message, then drop the oldest messages until total_tokens <= token_limit.""" if message.tokens < 0: raise ValueError("token counts cannot be negative") # Phase 1: append the newest message on the right in O(1) and update the running sum. self._messages.append(message) self.total_tokens += message.tokens # dropped: evicted Message objects in eviction order [oldest_dropped, ...]. dropped = [] # Phase 2: use strict '>' because total_tokens == token_limit still fits. # Since system_message.tokens <= token_limit, popping all of self._messages (including # an oversized new message) brings total_tokens <= token_limit before the deque is empty. while self.total_tokens > self.token_limit: oldest = self._messages.popleft() self.total_tokens -= oldest.tokens dropped.append(oldest) return dropped def messages(self) -> List[Message]: """Return [system_message] (if present) followed by kept messages oldest first.""" result = [] if self.system_message is not None: result.append(self.system_message) result.extend(self._messages) return result def __len__(self) -> int: """Number of kept non-system messages.""" return len(self._messages)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine assembling a flipbook delivered one envelope (page) at a time, where each envelope contains a slip of paper — a cursor (an opaque server bookmark naming the next page) — until the final envelope arrives with None. Once you have the cards, you place them onto a conveyor belt sitting on a weight scale (token_limit): every new message goes onto the right end of the belt, and whenever the scale reads strictly above token_limit, the oldest cards drop off the left end one by one until the belt fits again. Storing the belt in a deque (double-ended queue, a container supporting O(1) appends on the right and O(1) pops from the left without shifting memory) alongside a running total_tokens integer makes keeping only the most recent fitting conversation suffix effortless.
Why do the naive approaches fail? For pagination, stopping as soon as a page list is empty (if not page: break) prematurely truncates conversations when the server filters deleted messages out of a middle page, and failing to record previously seen cursors turns a buggy server loop ("A" -> "B" -> "A") into an infinite hang. For compaction, calling sum(m.tokens for m in history) and list.pop(0) after every message scans and shifts all K kept messages on each turn, turning N turns into slow O(N * K) (O(N^2) worst-case) work.
Let's trace Examples 1 and 2 — paginating across an empty middle page and feeding turns into History(token_limit=12):
Pagination (Example 1):
fetch_page(None) -> ([u1:5, a1:4], next_cursor="cur_1") seen_cursors = {"cur_1"}
fetch_page("cur_1") -> ([], next_cursor="cur_2") empty page, keep going! seen = {"cur_1", "cur_2"}
fetch_page("cur_2") -> ([u2:6], next_cursor=None) None -> stop! Loaded [u1, a1, u2]
Compaction (Example 2, token_limit = 12):
add(t1:5), add(t2:4), add(t3:3) -> deque = [t1:5, t2:4, t3:3], total_tokens = 12 (<= 12, fits!)
add(t4:4) -> append t4:4 -> total_tokens = 16 > 12
-> popleft() evicts t1:5 -> deque = [t2:4, t3:3, t4:4], total_tokens = 11
add(t5:6) -> append t5:6 -> total_tokens = 17 > 12
-> popleft() evicts t2:4 (13 > 12), then t3:3 (10 <= 12) -> returns [t2, t3]
Complexity
Let N be the total number of messages fetched across P pages, and let K be the number of messages currently kept inside History.
iter_historyandload_history:- Time:
O(N + P)(without retries). We fetch each of thePpages once, check and insert its cursor in a hash set inO(1)average time, and yield each of theNmessages once (load_historyoptionally reverses theN-item list once at the end inO(N)time). With transient failures, each page makes at mostmax_attemptscalls. - Space:
O(P + B)foriter_history(whereBis one page's size) andO(N + P)forload_history.seen_cursorsstores up toPcursor strings,iter_historyholds only the current page in memory at a time, andload_historymaterializes allNmessages into a list.
- Time:
History.add(message):- Time:
O(1)amortized (O(1 + D)worst-case whenDold messages are evicted on that call). Appending to the right ofdequeand updatingself.total_tokenstakeO(1)time, and acrossMtotaladdcalls each message is appended once and popped viapopleft()at most once, so total evictions across allMcalls never exceedM. - Space:
O(K)persistent (plusO(D)returned for theDmessages evicted by that call), sinceself._messagesretains only the messages that currently fit withintoken_limit.
- Time:
History.messages()andlen(history):messages()takesO(K)time andO(K)space to copy the optional system message and theKkept messages into a fresh list for the caller;len(history)takesO(1)time andO(1)space.
Edge cases
- Empty conversation (
[([], None)]):fetch_page(None)yields zero items and returnsnext_cursor = None, soload_historycleanly returns[]. - Empty middle pages (
[([m1], "c1"), ([], "c2"), ([m2], None)]): Because onlynext_cursor is Noneterminates the loop,"c1"'s empty page is crossed without losingm2. - Direct or multi-hop cursor cycles (
"x" -> "x"or"A" -> "B" -> "A"): Storing all seen cursors in a set catches cycles of any length immediately withRepeatedCursorError(whereas comparing onlynext_cursor == cursorwould miss"A" -> "B" -> "A"). - Exact budget match (
total_tokens == token_limit): The loop conditionwhile self.total_tokens > self.token_limit:uses strict>, keeping histories that hit the limit on the nose. - Single oversized message (
message.tokens > remaining_budget): Every older non-system message and the new message itself are popped in FIFO order and returned byadd, leavingself._messagesempty (andsystem_messageintact if present). - Zero-token messages (
tokens == 0): Appended without evicting anything, and still evicted in chronological order whenever a later large message pushes older messages out. - Invalid configuration or negative token counts:
token_limit <= 0,system_message.tokens > token_limit, negativetokenson eithersystem_messageoradd(message), andmax_attempts < 1all raiseValueErrorimmediately.
Common mistakes
- Writing
while cursor:for pagination: Since the first request usescursor = None,while cursor:never executes even once. Usewhile True:and exit whennext_cursor is None. - Checking
seen_cursorsbeforeif next_cursor is None: returnwhile initializingseen_cursors = {None}: That misclassifies the normal end-of-streamNonecursor on the final page as a repeated cursor! Always return onnext_cursor is Nonefirst. - Retrying every exception or sleeping after the final failed attempt: Catching
Exceptioninstead ofTransientFetchErrorwastes backoff delays on permanent400 Bad RequestorValueErrorbugs, and sleeping before checkingattempt >= max_attemptsadds a pointless delay right before crashing. - Prepending reversed pages (
messages = page[::-1] + messages) fornewest_first=True: Copying the growing list on every page turnsO(N)loading intoO(N * P). Also ask in interviews whether a "newest-first" endpoint reverses messages within each page or only page order while keeping each page oldest-first. - Using
list.pop(0)orsum(...)insideHistory.add: Both turn fast amortizedO(1)updates intoO(K)work per turn. - Forgetting to validate
system_message.tokens: Allowingsystem_message.tokens > token_limitwould makewhile self.total_tokens > self.token_limit:pop from an empty deque (IndexError), and allowingsystem_message.tokens < 0would silently inflate the budget pasttoken_limit.
Alternative approaches
- Append-only log with prefix sums + binary search (
O(log N)query,O(N)memory): Keep every message ever added plus an array of prefix sums (cumulative token totalsprefix[i] = sum of first i messages). Finding the longest suffix whose tokens fitbudgetmeans finding the smallestiwithprefix[N] - prefix[i] <= budgetviabisect_leftinO(log N)time. This usesO(N)memory instead ofO(K), which is helpful when you also want an in-memory audit log of dropped turns. - Lazy newest-first pagination with early stop: When initializing
Historyat startup from a huge stored thread, if the backend supports serving messages newest-first, iterate lazily withiter_historyand stop fetching pages as soon as accumulated tokens reachtoken_limit - system_tokens. For a 10,000-message thread where only the latest 250 messages fit, that fetches ~3 pages instead of 100.
Follow-up questions
- Suppose evicted turns must be condensed into a running summary rather than deleted outright—how would you redesign eviction and reserve space for the summary itself? Pin a rolling
summary_messageslot right aftersystem_messageand carve out a dedicated token reserveRfor it so the live turn budget becomestoken_limit - system_tokens - R(enforced viamax_tokens=Ron the summarizer request, then recording the actual returned summary token count). Because invoking an LLM summarizer on every turn is slow and costly, batch compaction using hysteresis (high/low watermarks): when live turns cross 100% of their budget, pop oldest turns down to ~70% of that budget and fold those popped turns (whichaddalready returns!) together with the prior summary into an updated summary. For example, withtoken_limit = 8,000,system = 500, andR = 500, crossing7,000turn tokens trims the deque to~4,900tokens so summarization only fires once every~2,100new tokens. - How would you adapt the sliding buffer so an assistant's function invocation and its corresponding output are always retained or evicted as an indivisible unit? Store atomic turn groups
(group_messages, group_tokens)insideself._messagesinstead of bareMessageobjects — for instance,[assistant_tool_call, tool_output_1, tool_output_2]paired with their combined token sum. Eachpopleft()then removes the entire group together so the prompt never contains an orphaned tool output without its call or a dangling tool call missing its outputs (both of which LLM chat APIs reject with 400 validation errors). While tool executions are still running asynchronously, stage the open group in a pending buffer outside the deque and append the sealed group once every tool output returns. - If live turns keep arriving while a client is still walking backward through historical pages, how do you prevent missing or duplicated entries? Avoid offset pagination (
OFFSET 20 LIMIT 20on a newest-first feed), where inserting one live turn shifts every older item's index by+1and duplicates the boundary turn across consecutive pages (while a deletion shifts indices by-1and skips a turn). Instead, anchor cursors with keyset pagination on an immutable sort key such as(created_at, message_id) < cursor_keyso live inserts at the newest end never move historical page boundaries. On the client, open the real-time event subscription before requesting page 1, buffer incoming live turns during pagination, and deduplicate bymessage.idwhere the historical backfill meets the live buffer. - How can you verify retry timing, cursor-cycle guards, and lazy page loading in unit tests without hitting a real backend? Inject
fetch_pageandsleepas callable parameters rather than hard-coding HTTP clients andtime.sleep, just as our implementation does. Pair them in tests with an in-memory fake source mapping each cursor to(page, next_cursor)plus scripted per-cursor failure queues and a maximum call-count assertion so an infinite loop fails in milliseconds instead of hanging CI. That lets fast unit tests deterministically assert empty middle pages,"c1" -> "c1"and"p1" -> "p2" -> "p1"cycle detection, exact backoff schedules like[0.1, 0.2], non-retryable exception propagation, and lazy page-fetch counts alongside a single recorded-fixture test verifying backend wire schemas.
Follow-up questions
- Suppose evicted turns must be condensed into a running summary rather than deleted outright—how would you redesign eviction and reserve space for the summary itself?
- How would you adapt the sliding buffer so an assistant's function invocation and its corresponding output are always retained or evicted as an indivisible unit?
- If live turns keep arriving while a client is still walking backward through historical pages, how do you prevent missing or duplicated entries?
- How can you verify retry timing, cursor-cycle guards, and lazy page loading in unit tests without hitting a real backend?
Similar questions
- Paginated Record Collection and Token-Budget Compaction
- Paginated Conversation Loader with Suffix Token Trimming
- Drain Paginated Logs and Compact to a Byte Limit
- Design a Resilient AI Customer Support Chat Platform
- Header-Preserving Markdown Chunker
- Dynamic Dynasty Succession Without an Initial Monarch