Case-Insensitive Ticket Queue Filtering and UI State Debugging
Medium · Software Engineering Fundamentals · Frontend Engineer · Technical Screen
Problem Statement
You inherit a browser-based issue triage dashboard built in a component UI framework (such as React). The existing interface already renders:
- Two status views:
"unresolved"and"archived". - A list of ticket rows displaying each item's metadata and owner.
- A text search field at the top that is not wired to any state yet.
- A right-hand detail drawer that displays a ticket's timeline when a user selects a row.
The exercise has two parts:
- Implement case-insensitive queue filtering: Wire the search input as the sole new piece of stored UI state and derive the visible rows from
(tickets, active_tab, query)without duplicating list state. Specifically, implement the pure filtering helper evaluated by the automated judge:
def filter_tickets(
tickets: List[Dict], active_tab: str, query: str
) -> List[Dict]:
pass
Each element of tickets is a dictionary with keys "id" (int), "status" ("unresolved" or "archived"), "title" (str), and "assignee" (str or None when no owner is assigned). Return a new list preserving original relative order (without mutating tickets) according to these exact rules:
- Tab scoping: Only items where
ticket["status"] == active_tabmay appear; items in the inactive view are always excluded, whilequerypersists across tab switches in the UI. - Outer whitespace trimming: Strip leading and trailing whitespace from
query(preserving internal spaces). If the trimmed query is empty, return every ticket inactive_tab, including unassigned ones. - Case-insensitive literal substring match: A non-empty trimmed query matches a ticket when it occurs as a contiguous substring anywhere inside
ticket["title"]or anywhere insideticket["assignee"], ignoring letter case via Unicode case-folding and treating punctuation literally (not as regular-expression syntax). A query cannot match by spanning across the end oftitleand the start ofassignee. - Unassigned items: When
ticket["assignee"]isNone, the ticket can match only via an empty query or itstitle(never via the literal string"none").
- Diagnose and fix three UI regressions: Outline how to reproduce, inspect in developer tools, and resolve the root causes behind three reported defects without breaking search:
- Defect A: Selecting a row — particularly while a search filter is active — opens a different ticket inside the right-hand detail drawer.
- Defect B: Navigating from the
"unresolved"view to"archived"leaves an"unresolved"ticket displayed inside the detail drawer. - Defect C: Displayed rows trail behind user input by a single character (for instance, entering
"we"still renders matches for"w").
Examples
Example 1
Input:
tickets = [
{"id": 10, "status": "unresolved", "title": "Webhook timeout on checkout", "assignee": "Maya"},
{"id": 11, "status": "unresolved", "title": "Invoice PDF formatting", "assignee": "Liam"},
{"id": 12, "status": "archived", "title": "Legacy webhook retry", "assignee": "Noah"}
]
active_tab = "unresolved"
query = "WEBHOOK"
Output:
[
{"id": 10, "status": "unresolved", "title": "Webhook timeout on checkout", "assignee": "Maya"}
]
Explanation: Ticket 10 belongs to "unresolved" and "Webhook timeout on checkout" contains "webhook" case-insensitively. Ticket 11 does not contain "webhook", and ticket 12 is skipped because its status is "archived".
Example 2
Input:
tickets = [
{"id": 21, "status": "unresolved", "title": "TLS certificate renewal", "assignee": None},
{"id": 22, "status": "unresolved", "title": "SSO redirect loop", "assignee": "Priya"},
{"id": 23, "status": "archived", "title": "Rotate staging keys", "assignee": "Priya"}
]
active_tab = "unresolved"
query = " "
Output:
[
{"id": 21, "status": "unresolved", "title": "TLS certificate renewal", "assignee": None},
{"id": 22, "status": "unresolved", "title": "SSO redirect loop", "assignee": "Priya"}
]
Explanation: Stripping whitespace from " " yields "", so every "unresolved" ticket is kept in order — including unassigned ticket 21 — while "archived" ticket 23 stays hidden.
Example 3
Input:
tickets = [
{"id": 31, "status": "unresolved", "title": "API rate limit spike", "assignee": "Carlos"},
{"id": 32, "status": "archived", "title": "Search index rebuild", "assignee": "Elena"},
{"id": 33, "status": "archived", "title": "Audit log retention", "assignee": None}
]
active_tab = "archived"
query = " lEn "
Output:
[
{"id": 32, "status": "archived", "title": "Search index rebuild", "assignee": "Elena"}
]
Explanation: Trimming " lEn " produces "lEn", which matches inside "Elena" on "archived" ticket 32. Ticket 31 is in "unresolved", and unassigned ticket 33 has no match in its title.
Constraints
0 <= len(tickets) <= 10^4active_tabis"unresolved"or"archived".- Each
ticketdictionary contains"id"(int),"status"(str),"title"(str), and"assignee"(Optional[str]). 0 <= len(query), len(ticket["title"]) <= 500- Neither
ticketsnor any dictionary inside it may be mutated.
Step-by-step walkthrough
Understand the dashboard layout and filtering rules
We are extending an issue triage dashboard across two parts: building case-insensitive text filtering (Part 1) and resolving three UI state defects (Part 2).
+-------------------------------------------------------------------------+ | [ Unresolved ] [ Archived ] | | Search: [ WEBHOOK ] | +-----------------------------------------+-------------------------------+ | Visible Ticket List | Detail Drawer (right side) | | - #10 Webhook timeout... (Maya) <-click+-> Ticket #10 timeline | +-----------------------------------------+-------------------------------+The automated judge evaluates Part 1's core logic via
filter_tickets(tickets, active_tab, query):- Inputs:
tickets: list of dictionaries like{"id": 10, "status": "unresolved", "title": "Webhook timeout on checkout", "assignee": "Maya"}. Unassigned tickets store"assignee": None.active_tab:"unresolved"or"archived".query: raw text currently inside the search input.
- Output: a new list containing matching ticket dictionaries in their original relative order, without mutating
tickets.
Four exact matching rules govern the filter: 1. Active tab only: Only items where
ticket["status"] == active_tabcan appear (Example 1 hides"archived"ticket#12even though its title contains"webhook"). 2. Trim outer spaces: Leading and trailing whitespace is stripped, so" "behaves like an empty query and returns the entire active tab (Example 2), whereas spaces inside a phrase must still match. 3. Literal substring anywhere, ignoring case: A non-empty trimmed query matches if it occurs anywhere insidetitleor anywhere insideassignee, regardless of uppercase or lowercase letters (Examples 1 and 3). 4. Unassigned tickets: WhenassigneeisNone, the ticket can match viatitle(or an empty query), and must never match the word"none"through its missing owner.- Inputs:
Separate stored state from derived state
Before writing code, decide what belongs in component state. In frontend architecture, stored state is the minimal set of raw values held in memory that cannot be computed from anything else, while derived state is any value computed on the fly from stored state during rendering.
Stored state (single source of truth): tickets + activeTab + query (ONLY new state!) + selectedId \ | / | v v v v visibleTickets = filter_tickets(...) selectedTicket = find in visibleTickets (derived, never stored) (derived, never stored)Why avoid storing
filteredTicketsin its own state variable? Because typing in the search field, switching tabs, or receiving updated tickets all change which rows are visible. IffilteredTicketsis stored separately, forgetting to recompute it in even one event handler leaves the screen out of sync. Scanning a few hundred or thousand in-memory tickets per keystroke takes well under a millisecond, so derivingvisibleTicketsdirectly is both fast and bug-free.Normalize text safely (including unassigned tickets)
Case-insensitive comparison requires normalizing both the query and each ticket field first. Two traps appear immediately when
"assignee"isNone:- Calling
None.lower()raises anAttributeErrorin Python (orTypeErrorin JavaScript). - Calling
str(assignee).lower()convertsNoneinto"none", making a search fornonefalsely return every unassigned ticket!
Mapping
Noneto""solves both issues cleanly: a non-empty query is never a substring of"", so an unassigned ticket simply misses onassigneeand relies ontitle.For case normalization, Python's
str.casefold()performs full Unicode case-folding (converting text into a canonical lowercase representation built specifically for case-insensitive matching, turning"WEBHOOK"into"webhook"and handling international characters such as"ß"->"ss").from typing import Optional def normalize_text(text: Optional[str]) -> str: """Convert text to a lowercase comparable form; map None to '' safely.""" # Unassigned tickets have assignee=None. Mapping None -> "" avoids crashing on # .casefold() AND prevents str(None) from matching the search query "none". if text is None: return "" # casefold() performs full Unicode case-insensitive folding (e.g., "WEBHOOK" -> "webhook"). return text.casefold()- Calling
Check title and assignee separately
A tempting shortcut is concatenating both fields (
f"{title} {assignee}") and running oneincheck. Watch what breaks ontitle = "SSO redirect loop"andassignee = "Priya":Combined string: "sso redirect loop priya" ^^^^^^^^^^ Query "loop priya" matches across the boundary — even though NEITHER field contains "loop priya"!Testing
titlefirst andassigneesecond keeps field boundaries intact and treats punctuation literally (unlike an unescaped regular expression, which would misbehave on[URGENT]orC++).from typing import Dict def ticket_matches_query(ticket: Dict, normalized_query: str) -> bool: """Return True if normalized_query appears inside the title OR inside the assignee.""" # Check title and assignee separately rather than concatenating them, so a query # like "loop priya" cannot match across title="SSO redirect loop" and assignee="Priya". title_folded = normalize_text(ticket.get("title")) if normalized_query in title_folded: return True assignee_folded = normalize_text(ticket.get("assignee")) return normalized_query in assignee_foldedCombine tab filtering and search in one pass
Inside
filter_tickets, we strip outer whitespace and case-foldqueryonce before iterating so we do not repeat that work per row. For each ticket:- Skip rows whose
statusdiffers fromactive_tab. - Keep the row immediately when
normalized_query == ""(blank or whitespace-only input), or wheneverticket_matches_queryreturnsTrue.
Let's trace Example 1 (
active_tab = "unresolved",query = "WEBHOOK"->normalized_query = "webhook"):Ticket #10: status="unresolved" (ok) | title="webhook timeout on checkout" -> contains "webhook" -> KEEP Ticket #11: status="unresolved" (ok) | title="invoice pdf formatting", assignee="liam" -> DROP Ticket #12: status="archived" (no) | skipped immediately despite "legacy webhook retry" Result: [Ticket #10]And in Example 2 (
query = " "->normalized_query = ""), both"unresolved"rows are kept — including Ticket#21with"assignee": None— while"archived"Ticket#23is skipped.from typing import Dict, List def filter_tickets(tickets: List[Dict], active_tab: str, query: str) -> List[Dict]: # tickets: list of dicts like {"id": 10, "status": "unresolved", "title": "...", "assignee": "Maya" | None} # Phase 1: Trim outer whitespace and case-fold the query once before scanning the list. normalized_query = normalize_text(query.strip()) # Phase 2: Scan tickets in order, keeping those in active_tab that match the query. visible_tickets = [] for ticket in tickets: # Tab filter comes first: tickets from the inactive tab stay hidden even if their text matches. if ticket.get("status") != active_tab: continue # A blank/whitespace-only query keeps every ticket in the active tab (including assignee=None). if normalized_query == "" or ticket_matches_query(ticket, normalized_query): visible_tickets.append(ticket) return visible_tickets- Skip rows whose
Wire the filter into a component-based UI
In a component framework such as React, bind the search box as a controlled input (an input element whose displayed text comes directly from component state via
value={query}and updates state ononChange). OnlyuseStateanduseMemobelow are React-specific; Vue (computed) and Svelte ($derived) follow the exact same state model.function TicketQueue({ tickets }) { const [activeTab, setActiveTab] = useState("unresolved"); const [query, setQuery] = useState(""); // the ONLY new piece of state const [selectedId, setSelectedId] = useState(null); // Derived list: always consistent with tickets, activeTab, and query. const visibleTickets = useMemo( () => filterTickets(tickets, activeTab, query), [tickets, activeTab, query] ); // Derived drawer selection: clears automatically if tab change or search hides the row. const selectedTicket = visibleTickets.find((t) => t.id === selectedId) ?? null; return ( <> <Tabs value={activeTab} onChange={setActiveTab} /> <input type="search" aria-label="Filter tickets by title or assignee" value={query} onChange={(e) => setQuery(e.target.value)} /> {visibleTickets.length === 0 ? ( <p>No matching tickets found.</p> ) : ( <ul> {visibleTickets.map((t) => ( <TicketRow key={t.id} ticket={t} onClick={() => setSelectedId(t.id)} /> ))} </ul> )} {selectedTicket && <DetailDrawer ticket={selectedTicket} />} </> ); }Notice how UI interactions fall into place naturally: - Switching tabs:
querysits above the tab bar, so switching views retains the typed filter and immediately applies it to the newly selected tab. - Detail drawer:selectedTicketis resolved againstvisibleTickets, so whenever a filter or tab switch hides the selected item, the drawer closes rather than displaying a hidden ticket. - Zero matches: Rendering"No matching tickets found."communicates that filtering succeeded rather than looking like a broken blank screen.Diagnose and fix the three UI regressions
Approach each bug report with a disciplined five-step loop: Reproduce with a minimal click/keystroke sequence -> Hypothesize which state invariant was violated -> Inspect state, props, and network activity in DevTools -> Fix the root cause -> Retest both the regression and Part 1 filtering.
Defect A: Clicking a filtered row opens the wrong ticket in the detail drawer
- Reproduce: Enter a query that hides row
0, then click the top visible row; observe that the drawer displays hidden row0instead. - Root cause (array position vs. stable ID): Row clicks stored a list index
onClick={() => setSelectedIndex(i)}fromvisibleTickets, while the drawer indexed into the unfilteredtickets[selectedIndex]array (or rows usedkey={i}, causing React to reuse row-local state across mismatched items):
All tickets: [0] #11 Invoice PDF (Liam) [1] #10 Webhook timeout (Maya) Filtered ("webhook"): [0] #10 Webhook timeout (Maya) <-- click index 0; tickets[0] opens #11!- Fix: Store
selectedId(ticket.id), look up the drawer's ticket viat.id === selectedId, and render rows withkey={ticket.id}.
Defect B: Switching tabs leaves an item from the previous tab open in the drawer
- Reproduce: Select an
"unresolved"row so its drawer opens, then switch to"archived". - Root cause (stale or unscoped selection): Either the app saves a separate
selectedTicketobject in state, or it looks upselectedIdinside the fullticketsarray without verifying membership inactiveTab. - Fix: Derive
selectedTicketfromvisibleTickets(visibleTickets.find(t => t.id === selectedId)), and optionally resetsetSelectedId(null)inside the tab-change handler if returning to the prior tab should not reopen the old selection.
Defect C: Visible rows trail one character behind the input field (typing
"we"displays matches for"w")- Reproduce: From a blank input, type
wand thene, inspectingqueryand rendered rows after each character. - Root causes & fixes (verify in DevTools):
- Reading stale state inside
onChange: CallingsetQuery(e.target.value)and immediately callingsetVisible(filterTickets(tickets, activeTab, query))reads the previous render'squeryvalue ("w"), because React state setters schedule the next render asynchronously. Fix: Removevisiblestate and derivevisibleTicketsduring render. - Listening to
onKeyDowninstead ofonChange: Readinge.target.valueduringkeydownexecutes before the browser insertseinto the text field. Fix: Bind a controlled input usingonChange. - Out-of-order network responses (when search hits an API): If an earlier slow request for
"w"resolves after a faster request for"we", it overwrites newer results (reproducible with Network throttling). Fix: Abort superseded requests viaAbortControlleror discard responses with stale request sequence numbers.
- Reading stale state inside
- Reproduce: Enter a query that hides row
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def normalize_text(text: Optional[str]) -> str: """Convert text to a lowercase comparable form; map None to '' safely.""" # Unassigned tickets have assignee=None. Mapping None -> "" avoids crashing on # .casefold() AND prevents str(None) from matching the search query "none". if text is None: return "" # casefold() performs full Unicode case-insensitive folding (e.g., "WEBHOOK" -> "webhook"). return text.casefold() def ticket_matches_query(ticket: Dict, normalized_query: str) -> bool: """Return True if normalized_query appears inside the title OR inside the assignee.""" # Check title and assignee separately rather than concatenating them, so a query # like "loop priya" cannot match across title="SSO redirect loop" and assignee="Priya". title_folded = normalize_text(ticket.get("title")) if normalized_query in title_folded: return True assignee_folded = normalize_text(ticket.get("assignee")) return normalized_query in assignee_folded def filter_tickets(tickets: List[Dict], active_tab: str, query: str) -> List[Dict]: # tickets: list of dicts like {"id": 10, "status": "unresolved", "title": "...", "assignee": "Maya" | None} # Phase 1: Trim outer whitespace and case-fold the query once before scanning the list. normalized_query = normalize_text(query.strip()) # Phase 2: Scan tickets in order, keeping those in active_tab that match the query. visible_tickets = [] for ticket in tickets: # Tab filter comes first: tickets from the inactive tab stay hidden even if their text matches. if ticket.get("status") != active_tab: continue # A blank/whitespace-only query keeps every ticket in the active tab (including assignee=None). if normalized_query == "" or ticket_matches_query(ticket, normalized_query): visible_tickets.append(ticket) return visible_tickets✅ Submit now — all tests should pass.
Intuition & how it works
Think of filtering an issue queue like placing two transparent stencils over a master ledger: the first stencil masks out every row outside active_tab, and the second masks out every row whose title and assignee both miss the search text. You never duplicate, sort, or mutate the master ledger as someone types — instead, you store only the raw search input (query) and compute the visible rows on the fly from (tickets, active_tab, query). In frontend engineering, this principle is called derived state (computing displayed collections directly from source-of-truth state during rendering rather than maintaining a second copy that can drift out of sync).
Why do naive shortcuts introduce bugs? Saving filteredTickets in its own state variable alongside query forces every tab switch, keystroke, and data refresh to synchronize two arrays manually — and reading query right after setQuery(...) inside an event handler sees the previous keystroke's snapshot, causing a one-character lag. Meanwhile, concatenating title + " " + assignee allows phrases to match falsely across the seam between fields, and calling str(assignee) on an unassigned item (None) causes searching "none" to match every unassigned row.
Let's trace Example 1 (active_tab = "unresolved", query = " WEBHOOK "):
Step 1 — Normalize query once: " WEBHOOK ".strip().casefold() --> "webhook"
Step 2 — Scan tickets in order:
Ticket #10 {status: "unresolved", title: "Webhook timeout on checkout", assignee: "Maya"}
-> status matches tab; folded title contains "webhook" --> KEEP
Ticket #11 {status: "unresolved", title: "Invoice PDF formatting", assignee: "Liam"}
-> status matches tab; neither "invoice pdf formatting" nor "liam" matches --> SKIP
Ticket #12 {status: "archived", title: "Legacy webhook retry", assignee: "Noah"}
-> status != "unresolved" (rejected before string checks) --> SKIP
Output: [Ticket #10]
Complexity
Let n be the number of tickets, L be the maximum character length of a title or assignee string, and q be the length of the trimmed query.
- Time:
O(n * L * q)in the theoretical worst case, andO(n * L)in practice on everyday titles and queries. We normalizequeryonce inO(q)time, then scan each of thentickets once: inactive-tab tickets takeO(1)to skip, while active-tab tickets case-fold up to two strings of length<= L(O(L)) and run C-level substring checks. - Space:
O(n + L + q). The output list holds up tonreferences to existing ticket dictionaries (without copying the dictionaries), while case-folding one field and the query allocates temporary strings of sizeO(L + q).
Edge cases
- Empty or whitespace-only query (
""," ","\t\n"): Trimming yields"", keeping every ticket inactive_tab— including unassigned tickets withassignee = None. - Unassigned tickets (
assigneeisNone): MappingNoneto""avoidsAttributeErrorcrashes and ensures"none"only matches rows whose title or owner genuinely contains the letters"none". - Internal spaces in queries (
"redirect loop"):.strip()removes outer whitespace only; spaces inside a multi-word phrase must still match. - Cross-field phrases (
"loop priya"on title"SSO redirect loop", assignee"Priya"): Checkingtitleandassigneeindependently returnsFalseso queries never bridge across the two fields. - Punctuation and regex metacharacters (
"[urgent]","c++","v2.1"): Plain substringinmatches characters literally, whereas an unescaped regular expression would misinterpret[,+, or.. - Tab isolation, empty queues, and immutability: Matching text in the inactive tab stays hidden, empty matches return
[], and returned items preserve input order without modifyingtickets.
Common mistakes
- Case-folding only one side (
query.lower() in ticket["title"]): Uppercase letters intitle("Webhook timeout") then fail to match"webhook". Both sides must be normalized. - Converting
Noneviastr(ticket["assignee"])or omitting theNonecheck: Either crashes on.casefold()or turnsNoneinto"None", matching"none"on unassigned tickets. - Joining
titleandassigneeinto one string: Produces phantom matches spanning the end oftitleand the beginning ofassignee. - Storing
filteredTicketsorselectedTicketas separate component state: Triggers one-character input lag (reading stale state insideonChange) and leaves hidden tickets open in the drawer after switching tabs. - Tracking selection or React
keyby array index (selectedIndex,key={index}): Once filtering hides earlier items, index0invisibleTicketsno longer corresponds to index0intickets, opening the wrong ticket in the detail drawer.
Alternative approaches
- Precomputed folded strings: Attach
title_foldedandassignee_foldedonce when tickets load so each keystroke runs substring checks without re-allocating lowercase strings — helpful for thousands of rows, as long as edits refresh those cached fields. - Word-prefix matching: If product specs want
"ind"to match"Search index"but not"Window", split each folded field on whitespace and checkword.startswith(normalized_query)instead of general substringin.
Follow-up questions
- If the ticket backlog scales to 50,000+ rows, how would you keep both filtering and DOM rendering responsive? Mounting 50,000 DOM nodes stalls browser layout long before string matching becomes the bottleneck, so introduce list virtualization (also called windowing — rendering only the ~20 rows currently inside the scroll viewport via
react-windowor TanStack Virtual) with stablekey={ticket.id}props. For filtering, precompute case-foldedtitleandassigneestrings once on load, and keep typing responsive withuseDeferredValue(query)or debouncing (delaying expensive recomputation until ~150 ms after typing pauses). Once the backlog is too large to ship to the client, move search to a paginated backend endpoint backed by a trigram index and abort in-flight requests on newer keystrokes. - How would you safely render visual highlights around matched substrings in a ticket's title or assignee name? Escape regex metacharacters in the trimmed query (
q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), locate match boundaries directly on the original string with a case-insensitive regular expression, slice the string into[before, match, after]segments, and render<mark>{match}</mark>as framework nodes. Never inject raw HTML strings viainnerHTMLordangerouslySetInnerHTML, which introduces cross-site scripting (XSS) vulnerabilities (letting untrusted titles like<img onerror=...>run scripts), and compute offsets on the original string rather than.toLowerCase()because certain Unicode characters change length when lowercased. - How would you synchronize the active tab and search query with the browser URL so filtered views can be bookmarked and refreshed? Persist both values in URL query parameters (for example
?tab=archived&q=webhook) through your router's search-parameter hook (useSearchParams) or the History API (URLSearchParams+popstatelistener). Usereplacehistory updates on keystrokes so typing a word does not flood the Back button with one entry per character, and usepushupdates on tab changes so Back steps naturally between tabs. Validate URL parameters on initial load, defaulting unknowntabvalues to"unresolved"and missingqvalues to"". - Which unit, integration, and regression tests would you add to cover the search filter and the three UI defects? Write pure unit tests on
filter_ticketscovering mixed letter case, assignee-only matches,assignee=None(including searching"none"), blank/padded queries, cross-field non-matches, regex punctuation, and inactive-tab exclusion. Complement them with UI component tests (such as Testing Library) and one dedicated regression test (an automated test reproducing a previously fixed defect so it cannot reappear) per Part 2 bug: (1) filter out row0, click the first visible row, and assert the drawer renders that ticket's ID; (2) open an"unresolved"row, switch to"archived", and assert the drawer closes; (3) type"w"then"e"and assert after each keystroke that visible rows immediately reflect"w"and"we", plus a mocked out-of-order async response test when search uses network calls.
Follow-up questions
- If the ticket backlog scales to 50,000+ rows, how would you keep both filtering and DOM rendering responsive?
- How would you safely render visual highlights around matched substrings in a ticket's title or assignee name?
- How would you synchronize the active tab and search query with the browser URL so filtered views can be bookmarked and refreshed?
- Which unit, integration, and regression tests would you add to cover the search filter and the three UI defects?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes
- Key-Value Store with Sliding-Window Read and Write Rates