Debugging Catalog Search Gaps and Inventory State Bugs
Easy · Software Engineering Fundamentals · Software Engineer · Online Assessment
Prompt
You have just taken over maintenance of a web-based library catalog that lets patrons search titles, narrow results with filters, and check copies in and out. Support tickets report two recurring problems: certain searches fail to surface all matching titles, and certain views display out-of-date or inaccurate copy availability.
Walk through your end-to-end engineering approach to investigate, isolate, and fix these issues. Assume two ground rules:
- No codebase or pre-packaged failing test is provided, so do not invent a single made-up bug and pretend that was the cause; instead, show how your diagnostic checks branch based on what you observe.
- Restricted AI-assistant policy: you may ask an AI assistant to explain unfamiliar code sections or help locate relevant files, but you may not ask it to diagnose the bug on its own or write/apply the fix for you.
Scope & Expectations
- Clarification & deterministic reproduction: Specify the exact questions and data points needed to turn vague bug tickets into repeatable test cases (search terms, active filter combinations, checkout/return steps, expected vs. actual counts, and whether the bad values appear in raw API responses, client-side memory, or both).
- Layer-by-layer isolation: Show how to bisect the data path from database tables through backend serialization to browser state and UI rendering before editing application code.
- Hypothesis testing for search and inventory: Cover the primary mechanisms behind missing search results and inaccurate copy counts—both stale read paths and broken concurrent writes—along with test-first verification of each fix.
- Disciplined AI verification: Explain how to use an AI assistant strictly for code navigation and explanation while cross-checking every claim against actual runtime behavior and repository searches.
Step-by-step walkthrough
Turn vague tickets into reproducible test cases
Vague complaints about missing titles or inaccurate copy counts cannot be fixed safely by guessing. Before touching code, clarify the exact failure conditions and convert each ticket into a deterministic reproduction with a concrete expected count. Without a repeatable check, you cannot prove what caused the defect or confirm that your patch resolved it.
For each reported issue, gather four concrete details:
- Exact query inputs: search phrase, selected filter options, sort field, page number, page size, and patron role.
- Exact inventory transition (for availability bugs): step-by-step actions such as "start with 4 available copies, check out 1 copy, navigate back to the catalog list, then open the item detail view."
- Expected vs. observed numbers: exact counts verified against storage rather than subjective impressions.
- Captured network call: copy the raw HTTP request from browser developer tools so you can replay it directly against the backend without clicking through the UI.
Without a live repository in front of us, the two sample reproductions below show the exact structure we will trace across the rest of the investigation:
Case S1 (Missing Search Titles) Input: query = "databases", subject = Computer Science, filter = in_stock_only, page_size = 15 Expected: 34 matching titles total (confirmed via a direct SQL count) Observed: 19 titles total across all pages; the first 15 matching titles never appear Case K1 (Out-of-Sync Copy Availability) Setup: Item #42 starts with 4 total copies and 4 available copies Action: Check out 1 copy of Item #42, then inspect the catalog list and the item detail view Expected: Both views display 3 available copies Observed: Detail view displays 3 available, while the catalog list still displays 4Split the data pipeline to find the first broken layer
Every search list or availability badge travels through four checkpoints from disk to screen. Rather than reading files at random, inspect the data at these boundaries to find the exact step where accurate data turns wrong:
[Database Rows] --SQL/index--> [API Response] --fetch/store--> [Browser State] --render--> [Screen] (A) (B) (C) (D)Here, serialization is the backend step that turns database records into JSON text for the HTTP response, and browser state (or client-side state) is the in-memory JavaScript store that drives UI rendering.
Inspect
(B)first by replaying your saved HTTP call, because one check cuts the system in half:- If
(A)is already wrong: the write path stored bad data (for instance, checking out a book failed to decrement the stored counter). Investigate backend write handlers. - If
(A)is right, but(B)is wrong: the backend read path is faulty (query predicates, page-offset math, stale server cache, or JSON serialization). - If
(B)is right, but(C)or(D)is wrong: the frontend is faulty (wrong query parameters sent, stale client-side cache, or a rendering defect).
Investigate each symptom separately: Case S1 and Case K1 often sit in completely different layers.
- If
Check pagination, filter logic, and text matching for missing search results
Once you narrow missing search hits to the backend query or frontend request layer, check the three mechanisms that routinely drop matching records.
1. Pagination bugs
Pagination divides a large match set into fixed-size slices using a limit and an offset (the number of rows skipped before a page starts).
- Off-by-one offset: if the UI numbers pages from
1(page = 1, 2, 3), while the backend calculatesoffset = page * page_size, thenpage = 1skips rows0..14and begins at row 16! Watch how that reproduces Case S1 (34matching rows,page_size = 15):
Database rows (34 matches, 0-based positions 0..33): [0 .. 14] [15 .. 29] [30 .. 33] 15 titles 15 titles 4 titles Buggy offset = page * 15: page 1 (offset 15) -> returns [15..29] (15 titles; [0..14] skipped!) page 2 (offset 30) -> returns [30..33] (4 titles) page 3 (offset 45) -> returns [] (19 titles seen instead of 34) Correct offset = (page - 1) * 15: page 1 (offset 0) -> returns [0..14] page 2 (offset 15) -> returns [15..29] page 3 (offset 30) -> returns [30..33] (all 34 titles seen)- Rounded-down page count: integer floor division
34 // 15yields2pages instead of3, hiding rows31..34. Round up with(total + page_size - 1) // page_size. - Unstable sort order:
ORDER BY title LIMIT 15 OFFSET 15without a unique tie-breaker lets identical titles shuffle unpredictably across pages, repeating some items and dropping others. Always endORDER BYwith a unique key such asORDER BY title ASC, id ASC. - Silent result caps: a hardcoded backend limit or search-engine default (such as returning at most 100 hits).
2. Filter composition bugs
- Swapped
AND/ORacross facets: a facet is a filter dimension such as Subject or Availability. Options inside one facet typically combine withOR(Databases OR Networking), whereas distinct facets combine withAND(subject AND in_stock). UsingANDinside a facet or overwriting URL query parameters (params = {"subject": "CS"}clobberingin_stock=true) drops valid matches. - Client-side filtering after server-side pagination: fetching 15 unfiltered rows for page 1 and hiding checked-out titles in JavaScript leaves page 1 sparse while stranding available titles on later pages.
- SQL
NULLtraps: SQL uses three-valued logic, where comparisons evaluate toTRUE,FALSE, orUNKNOWN, andWHEREretains onlyTRUErows. An exclusion check likeWHERE subject <> 'Poetry'evaluates toUNKNOWNwhensubjectisNULL, silently dropping uncategorized books unless writtenWHERE subject IS NULL OR subject <> 'Poetry'. - Row-dropping or row-multiplying joins: an
INNER JOIN authorshides books lacking an author row, whereas joining a one-to-manycopiestable beforeLIMIT 15repeats a multi-copy title and pushes other titles off the page.
3. Text matching and index freshness
- Case sensitivity (
Databasesvs.databases), punctuation/diacritics, stray whitespace, or exact equality (=) where substring matching (LIKE '%databases%') was expected. - A search index (a dedicated lookup store built for fast text queries) that missed updates when catalog rows were added or edited in the primary database.
A small diagnostic helper can walk every API page for a query and compare the returned IDs against the ground-truth IDs from SQL:
def page_offset(page: int, page_size: int) -> int: """Zero-based row offset for a 1-based page number.""" return (page - 1) * page_size def page_count(total_rows: int, page_size: int) -> int: """Total pages rounded up using exact integer ceiling division.""" if total_rows == 0: return 0 return (total_rows + page_size - 1) // page_size def audit_paginated_search(fetch_page, expected_ids, max_pages: int = 1000): """Walk 1-based API pages until empty and compare with database IDs.""" seen_ids = [] pages_fetched = 0 # Cap iterations in case a buggy server repeats the last page forever. while pages_fetched < max_pages: page_ids = fetch_page(pages_fetched + 1) if not page_ids: break seen_ids.extend(page_ids) pages_fetched += 1 duplicate_count = len(seen_ids) - len(set(seen_ids)) missing_ids = set(expected_ids) - set(seen_ids) return pages_fetched, duplicate_count, missing_idsDuplicates point to unstable sorting or row-multiplying joins; IDs missing from the very start point to an off-by-one offset; IDs missing across all pages point to filter or index bugs; and
pages_fetchedexceeding the UI's page controls points to rounded-down page counts.- Off-by-one offset: if the UI numbers pages from
Separate stale display state from a faulty inventory write
For inaccurate availability counts (Case K1), querying the database immediately after the checkout action tells you which half of the system failed.
Branch 1: Database says
3, screen says4(stale display state)Replay both the catalog-list API call and the item-detail API call:
- API says
3, browser shows4: the frontend held onto stale in-memory data. Typical culprits include separate client stores for list results versus detail views, an un-invalidated browser HTTP cache, or an optimistic update (updating the screen immediately before the server replies) wired up only on the detail view. A hard browser reload temporarily clears this symptom. - API itself still says
4: the backend read path returned outdated state despite the primary table holding3. Inspect un-invalidated application or CDN caches (edge servers caching HTTP responses), a lagging read replica (a read-only database follower that trails behind primary writes), or a list endpoint reading from a denormalized counter (a precomputed count stored in another table or search index) that the checkout handler never refreshed.
Branch 2: Database itself says
4or permits negative/overbooked copies (broken write)- Race condition / lost update: two checkout requests overlap, both read the old count before either commits, and the second overwrites the first:
Item #42 starts with available = 1: Patron A checkout Patron B checkout ----------------- ----------------- SELECT available -> reads 1 SELECT available -> reads 1 SET available = 1 - 1 (writes 0) SET available = 1 - 1 (writes 0) Result: 2 active loans recorded against only 1 physical copy!- Double click or network retry lacking an idempotency key (a unique request token ensuring retries execute at most once), subtracting two copies for a single checkout.
- Wrong column mutated, such as a check-in handler incrementing
total_copiesinstead ofavailable.
Audit copy integrity across the whole catalog with an invariant query (a rule that must always hold:
available = total_copies - active_loans):-- Keep returned_at IS NULL inside LEFT JOIN ON so titles with 0 active loans stay included. -- Use COUNT(l.id) instead of COUNT(*) so unmatched NULL loan rows count as 0, not 1. SELECT b.id, b.total_copies, b.available, COUNT(l.id) AS active_loans FROM books b LEFT JOIN loans l ON l.book_id = b.id AND l.returned_at IS NULL GROUP BY b.id, b.total_copies, b.available HAVING b.available <> b.total_copies - COUNT(l.id);When a lost update is confirmed, replace separate read-then-write steps with one conditional atomic
UPDATEinside the same database transaction (an all-or-nothing unit of database work) that inserts the loan row:-- Decrement atomically in SQL; if 0 rows update, stock was already 0 so roll back. UPDATE books SET available = available - 1 WHERE id = :book_id AND available > 0;- API says
Use the AI assistant to narrow the search, then verify every claim
Under the tooling policy, the AI assistant may explain unfamiliar code or help narrow which files to inspect, while you verify every claim and author the fix yourself.
Effective prompts ask concrete questions about code in front of you:
- "Walk through what SQL predicates this ORM builder emits when both
subjectandin_stock_onlyare set." (An ORM, or object-relational mapper, is a library that maps application classes and method calls onto SQL queries.) - "Which handlers, background jobs, or triggers in this module read or mutate
available?" - "How does this caching wrapper construct its cache key and TTL?"
Treat every assistant summary as an unverified lead until checked against runtime ground truth:
- Query summary: log the actual SQL string and bind values produced at runtime and run them against a local test database.
- "Nothing else writes
available": execute a repository-wide text search yourself to verify no cron worker, SQL trigger, or admin import touches that column. - "Pagination is 0-indexed": hit the local endpoint with
page=0andpage=1and inspect the returned IDs.
Never paste credentials, secrets, patron PII, or unapproved proprietary source into external tools, and whenever live execution disagrees with the assistant's summary, trust live execution.
- "Walk through what SQL predicates this ORM builder emits when both
Ship one focused fix at a time behind a failing test
Once runtime evidence confirms a root cause, resolve defects one at a time so each commit carries clear proof:
- Write a failing automated test first at the narrowest layer that reproduces the defect (unit test for page-offset math, database integration test for filter SQL or concurrent checkouts).
- Author the minimal fix yourself to turn that test green. Mixing pagination, filter, and cache changes in a single commit makes regressions hard to untangle.
- Run the full test suite, then replay the original end-to-end scenario (
S1orK1) against the API and browser UI. - Audit sibling endpoints sharing the same helper (such as author lookup or loan-history listings calling the same pagination function).
def test_all_pages_cover_every_match(): """34 matching titles at page size 15 must span 3 pages with zero missing or duplicate IDs.""" expected_ids = list(range(1, 35)) def fetch_page(page: int): start = (page - 1) * 15 return expected_ids[start:start + 15] pages, duplicates, missing = audit_paginated_search(fetch_page, expected_ids) assert pages == page_count(34, 15) == 3 assert duplicates == 0 assert missing == set()For concurrent checkout bugs, add an integration test that fires two simultaneous checkout calls against an item with
available = 1across two threads or sessions, asserting that exactly one succeeds, one rejects cleanly, andavailablefinishes at0.
Intuition & how it works
Debugging an unfamiliar web application is like finding where clean water turns muddy in a building's plumbing. Instead of randomly replacing kitchen faucets or digging up the street, a plumber opens test valves along the pipe from the water main to the sink; the very first valve with muddy water reveals the exact pipe segment that broke.
Guessing a root cause from the symptom alone ("it must be browser caching!" or "let's rewrite the search query!") fails because completely different bugs produce identical behavior on screen. Editing code before reproducing the defect with exact numbers also makes it impossible to tell whether your change solved the issue, did nothing, or broke another view.
Here is how the valve check works on a concrete scenario. Suppose Item #42 starts with 4 available copies, a patron checks out 1 copy, and afterward the detail view shows 3 available while the catalog list still shows 4:
- Inspect the database row:
SELECT available FROM books WHERE id = 42returns3. That immediately proves the checkout write path succeeded. - Replay the two API calls:
/api/books/42returns"available": 3, whereas/api/books?q=42returns"available": 4. - Pinpoint the broken segment: because the database holds
3and the list endpoint returns4, the browser UI is innocent — the list endpoint is serving stale data from a server cache, a lagging read copy, or an un-refreshed search index.
Key points
- Convert vague reports into numbered reproductions first. Capture the exact search terms, active filters, page parameters, checkout/return steps, raw HTTP request, and expected SQL count before editing code.
- Bisect the data path layer by layer. Data moves from database rows to the API payload (via serialization, which converts backend records into JSON), into browser state (in-memory JavaScript data), and finally onto the screen. Replaying the raw API call first cuts the search space in half.
- Check search-drop mechanisms systematically. Missing titles typically trace back to pagination math (an off-by-one offset, meaning the row count skipped before a page starts; rounded-down page counts; or
ORDER BYwithout a unique tie-breaker likeid), filter composition (swappingAND/ORacross facets, which are filter categories like subject; filtering in JavaScript after the backend already capped page 1; SQL three-valued logic droppingNULLvalues on<>predicates; or inner/one-to-many joins), or stale entries in a search index (a separate lookup store optimized for text queries). - Query storage immediately after inventory actions to split stock bugs. If the database count is accurate, look for stale state in the browser (split list/detail stores, HTTP cache, or a single-view optimistic update that updates the UI before the server replies) or on the server (CDN edge cache, lagging read replica, or an un-updated denormalized counter). If the database count itself is wrong, test for a concurrent race condition / lost update, a retried request missing an idempotency key (a unique token ensuring retries execute at most once), or mutating the wrong column.
- Encode domain invariants in SQL and test audits. Checking
available = total_copies - active_loansacross all rows and verifying that the union of all API pages equals the SQL match set surfaces silent data drift automatically. - Validate every AI summary and ship single-cause fixes. Restrict the assistant to explaining code (such as ORM queries that map application objects onto SQL) or locating candidate modules, verify every claim against runtime logs or repository searches, and write a failing test before authoring each minimal fix yourself.
Common mistakes
- Leaping straight to a pet hypothesis ("definitely client cache") and changing code before capturing a deterministic reproduction with exact expected counts.
- Testing search only on page 1 with a handful of seed rows. Off-by-one offsets, floor-divided page totals, and unstable tie-breakers only surface on multi-page datasets with tied sort values.
- Closing a ticket because a hard browser reload clears the wrong count. When refreshing fixes the display, storage is right and client-side state is stale — that confirms a frontend state-management bug rather than ruling one out.
- Testing checkouts strictly sequentially. A read-modify-write lost update passes single-user tests every time and only breaks under overlapping requests unless replaced by an atomic
UPDATE ... WHERE available > 0inside a database transaction (an all-or-nothing group of SQL statements). - Combining multiple speculative edits in one commit, hiding which change actually fixed the symptom and complicating rollbacks.
- Accepting an assistant's explanation of an ORM query or cache wrapper at face value without logging the emitted SQL or inspecting the live cache key.
Follow-up questions
- In what ways can page-slicing math or combined filter clauses silently drop matching catalog items? Page slicing loses items when a 1-based page number computes
offset = page * page_size(skipping page 1 entirely), when total page counts round down instead of up (hiding the trailing partial page), whenORDER BYomits a unique tie-breaker likeid(allowing tied titles to shift across page boundaries), or when an unspoken backend limit truncates results. Filter clauses lose items when options inside one category combine withANDinstead ofOR, when one query parameter overwrites another, when client code filters out items after the backend already returned a single page of 15 rows, whensubject <> 'Poetry'dropsNULLsubjects under SQL three-valued logic, or when an inner join drops titles missing related rows. Auditing all API pages until empty against a direct SQL query cleanly separates offset, tie-breaking, and predicate bugs. - What concrete checks tell you whether a wrong copy count comes from stale UI/cache state versus a faulty inventory write? Inspect the primary database row right after executing the checkout or return. When the database holds the expected number while the UI shows an older number, the write succeeded and a read layer is stale: replaying the raw API endpoint distinguishes stale browser memory (API already returns the new count) from a stale server cache, lagging read replica, or un-refreshed search index (API still returns the old count). When the database row itself holds the wrong number, the write path failed — run the
available = total_copies - active_loansinvariant query and fire concurrent checkout requests to expose lost updates or duplicate submissions. - How do you independently validate an AI tool's summary of unfamiliar backend or frontend code before acting on it? Turn each statement from the assistant into a fast, falsifiable check against the repository and running app. Print and execute the exact SQL and bind parameters produced by an ORM call, run a full-repo text search to confirm every caller and writer of a field, inspect live HTTP cache headers or debugger state during your local reproduction, or add a small unit test asserting the claimed edge-case behavior. Whenever runtime evidence disagrees with the assistant's explanation, follow the runtime evidence.
Follow-up questions
- In what ways can page-slicing math or combined filter clauses silently drop matching catalog items?
- What concrete checks tell you whether a wrong copy count comes from stale UI/cache state versus a faulty inventory write?
- How do you independently validate an AI tool's summary of unfamiliar backend or frontend code before acting on it?
Similar questions
- Catalog Search, Filtering, and Pagination
- Library Hold-Queue and Loan Reminder Notification Manager
- Fix Pre-Filter Summary Totals in a Reporting API
- Transit Simulation Efficiency Metric
- Priority Task Assignment System
- Resolve Signed Variable Equations with Error Detection
More Instacart interview questions
- Multi-Stage Cart Pricing, Best-Offer Selection, and Aisle Picking Medium
- Grocery Cart Totals, Best-Offer Promotions, and Store Picking Order Medium
- Inventory Reservations, Hot-SKU Scaling, and Oversell Control Medium Pro
- Multi-Location Inventory and Order-Picking System Medium Pro
- Resolve Target Variable Across Additive Assignment Chains Medium Pro
- Precedence-Aware Expression Evaluator Medium Pro
- Diagnosing a Marketplace KPI Drop Easy Pro
- Marketplace KPI Triage, Geo-Testing, and Retention Easy Pro
- Catalog Search, Filtering, and Pagination Medium Pro
- Library Hold-Queue and Loan Reminder Notification Manager Medium Pro