jn Joey Neleber
← All projects
CASE STUDY

Amazon Business Compare

A shared workspace for comparing Amazon Business and consumer prices, tracking offers over time, and deciding which changes deserve attention. The project connects catalog imports, scheduling, price history and notifications to a live dashboard.

Pythonprocessing pipelinedashboard templates

A comparison table is the front of a much larger system

The first idea is easy to describe: compare the Business cost of an item with its consumer price and surface an interesting difference. The implementation becomes much more demanding as soon as those numbers are supposed to mean the same thing. Is the offer new or refurbished? Does the price include shipping? Is it a single unit or a quantity tier? Is the consumer reference an actual Buy Box observation or a competitive-pricing metric with different semantics? The project is a useful learning story because those questions appear as source-level distinctions rather than being hidden inside one savings field.

The surviving platform separates core models, ingestion, processing, scheduling, notifications and API presentation. Python and FastAPI provide the server, SQLAlchemy describes the data model, SQLite WAL supports local persistence, and Jinja/HTMX renders a dense working dashboard without a client SPA. This is collaborative code: Joey-authored history supports substantial original implementation and later refinements, while Calum's later work changes both the operational behavior and which features remain. The portfolio story needs that timeline to explain the system accurately.

A2A route over a synthetic catalog, showing Business, third-party, dip and Grade-B examples.
A2A route over a synthetic catalog, showing Business, third-party, dip and Grade-B examples.

Learning to preserve the meaning of an offer

The Business response normalizer deliberately does not promote CompetitivePriceThreshold into a consumer price. It records Business Buy Box entries, extracts quantity minimums, preserves seller identity and leaves the consumer field empty until a separate consumer observation supplies it. It rejects non-new conditions and handles blocked sellers at ingestion rather than merely hiding their rows afterward. Where it falls through to another offer, it considers delivered cost, including shipping. These are data-modeling decisions: a number is useful only when its condition, source and seller still describe the offer being displayed.

The import path addresses another kind of ambiguity. Keepa exports contain formatted currency, percentages, missing markers, BOMs and alternative header spellings. The parser maps those into typed catalog fields, including separate package and item measurements. The current project's explicit rule makes package weight the decision field and keeps item weight as reference data. The offline reproduction parses a synthetic export and normalizes a synthetic Business response, then supplies a separate synthetic consumer response. No real account, ASIN catalog, marketplace request or seller credential is involved in that demonstration.

Keepa CSV and single-product import interface.
Keepa CSV and single-product import interface.

Current snapshots, historical observations and deal events are different facts

Product holds catalog identity, monitoring intent, listing eligibility and enrichment. PriceSnapshot represents the latest pricing state, while the leaner PriceHistory table supplies charts and baseline calculations. A latest-snapshot pointer avoids repeatedly searching an entire history to render a product row. Deal stores the current opportunity state and its observed metrics; DealActivityEvent records actual activation transitions. Keeping these concepts separate prevents a product's original discovery date from pretending to be the beginning of its current active streak.

A particularly useful design detail is that Business fetch time and consumer fetch time are independent. Updating the consumer side in place should not make a stale Business quote appear freshly polled. Snapshot provenance also survives when values are carried forward, with a maximum age on consumer reuse. History insertion compresses unchanged observations, which reduces repeated data but forces later algorithms to understand what the remaining timestamps mean. The offline run processes prices of 42, 99 and 38 against a synthetic consumer price of 100, observes active → inactive → active, and records three transition events. The returned deactivation counter remains zero on the middle step despite the state transition, a concrete reminder to inspect persisted state and events rather than trust one summary metric.

Inventory route and lifecycle navigation, using synthetic products, eligibility and check timestamps.
Inventory route and lifecycle navigation, using synthetic products, eligibility and check timestamps.
Gating route and read-only original query endpoints over synthetic restriction/candidate rows.
Gating route and read-only original query endpoints over synthetic restriction/candidate rows.

A nominal discount and a trustworthy baseline are not the same signal

The target predicate is intentionally simple and shared: an explicit dollar ceiling can match a consumer or quantity-tier price, and an explicit Business percentage target can match a tier's discount against the current consumer price. Either condition may activate the row. With neither target set, the item can be tracked silently. Quantity minimums remain values, not column-slot numbers; resolving a minimum of 100 means finding the stored slot whose minimum is 100, rather than looking for a nonexistent qty_100_price column.

The A2A clean-baseline path answers a different question: is this cost meaningfully below a plausible historical selling level? Its baseline function reads a longer window, excludes explicitly suppressed Buy Box samples, trims distorted highs, requires history spanning enough days and can hold when the remaining series is erratic. A blended short/long average keeps recent history relevant without allowing a recent spike to define normal. The current dashboard's clean-floor filter and SQS target-driven view deliberately do not have identical semantics. That distinction is documented in source and design notes and is more interesting than describing every row as a generic deal.

With too little history, the baseline calculation returns HOLD instead of a confident number. Sample runs show how it suppresses high-price outliers and keeps insufficient data visible.

History endpoint and Chart.js renderer comparing synthetic consumer/Business prices and BSR.
History endpoint and Chart.js renderer comparing synthetic consumer/Business prices and BSR.
An expanded original settings section exposes how monitoring and signal policy are configured.
An expanded original settings section exposes how monitoring and signal policy are configured.

Recurring windows require duration, not just tall points

The yo-yo detector looks for a different historical shape: retail prices that repeatedly rise above a cost-relative floor and stay there long enough to form meaningful windows. It requires distinct qualifying runs and aggregate hold time. It merges brief dips so one wobbling plateau does not become several events, ignores runs too short to count and caps how much an old pre-rise observation can contribute. This is a compact example of turning a visual chart judgment into an inspectable rule with a structured result.

Change-compressed history creates a subtle difficulty. A long unchanged plateau may survive as only one timestamp near its end, so measuring duration from the first surviving high point would erase the plateau. The detector uses a nearby below-floor anchor when appropriate to recover a bounded hold span. Its result reports counts, durations and supporting spikes as a human-review signal rather than an automatic purchase decision. In the synthetic offline series, four recurring windows satisfy the detector. That run verifies a constructed case, while the limitations of historical sampling remain part of the story.

Seven-day timeframe control applied to the same synthetic history.
Seven-day timeframe control applied to the same synthetic history.

Treat API capacity as a resource shared by several workflows

The scheduler cannot solve freshness by issuing every request immediately. It builds bounded batches, orders candidate ASINs, accounts for API rate limits and retries throttle failures with backoff. Token buckets are thread-safe and can adjust from observed response limits. Business polling, consumer refresh and event-driven verification have separate endpoint/budget considerations. A database session is not held while a rate-limited network call waits, and thread-local sessions avoid passing ORM state between workers.

Distributed probes add ownership to that scheduling problem. A shared ownership filter selects only the ASINs assigned to each fetcher, and reassignment uses a settling window so a new owner does not immediately overlap an old in-flight batch. The same ordering helper applies operator priorities and custom check intervals across master and probe paths. High priority should mean the same thing regardless of which machine owns the work. Failed products have counters and tier-sensitive retirement behavior, preventing indefinitely broken items from consuming the head of the queue.

The dashboard exposes the operator side of these rules through priority badges, custom intervals, lifecycle tabs, freshness and engine details. In this reproduction, rates are intentionally zero because no worker runs. That is more truthful than inventing a busy production engine for a screenshot. A separate, explicitly added queue-inspection page shows synthetic pending, completed and failed JobQueue records; it is a diagnostic output over the original model, not a claimed original dashboard screen.

High-priority query and per-product scheduling controls.
High-priority query and per-product scheduling controls.
Inactive view distinguishes paused and archived synthetic items.
Inactive view distinguishes paused and archived synthetic items.
Scheduler controls and budget explanation, with local dummy configuration and no running scheduler.
Scheduler controls and budget explanation, with local dummy configuration and no running scheduler.
Added read-only fixture inspector over the original JobQueue model.
Added read-only fixture inspector over the original JobQueue model.

Push notifications need persistence, deduplication and a recovery story

Offer-change events supply a push-driven lane alongside periodic polling. The source persists notification evidence, tracks the push-covered ASIN set and warms it from the database after restart. It uses verification cooldowns and throttle-specific retry logic so a noisy listing does not trigger unlimited follow-up work. Persisted coverage and real call-site wiring matter more than a comment claiming a retry exists; the current source explicitly records a historical case where retry constants had been written but not connected to the fetch path.

Delivery also changes over the project's life. The original Discord dispatcher is historical: September commits stop and remove that mechanism. Committed Telegram work instead reads the append-only activation log for custom-interval watched items, uses a watermark, avoids blasting the backlog on first startup and contains send failures so they do not stall scanning. The inspected working tree adds pending-event retry handling and a new untracked Discord candidate sender with freshness, direct eligibility, fee and cost gates. Those newer files show an experiment under development, not evidence of deployment, successful delivery or completed purchases. No notification function is called by the capture harness.

Push-covered synthetic products and per-row dollar/percentage targets, rendered by the actual inventory endpoint.
Push-covered synthetic products and per-row dollar/percentage targets, rendered by the actual inventory endpoint.
SQS deal queue with type/search controls and synthetic push-covered deals.
SQS deal queue with type/search controls and synthetic push-covered deals.

A live operational UI should preserve attention while data changes

The dashboard uses server-rendered rows and HTMX fragments rather than maintaining a second copy of the business model in client state. Shared Jinja filters and macros keep times, durations, prices, chips and table conventions consistent. Inventory separates catalog-management work from the active/past opportunity stream. Search and advanced filters serialize a common query state, and the current design keeps secondary controls in a drawer instead of endlessly widening the top bar. The local screenshots exercise these actual routes and SQL queries with a fresh synthetic catalog.

Real-time updates introduce their own design constraints. A thread-safe event bus bridges committed ORM changes into asynchronous SSE subscribers, while a structural version distinguishes row-set changes from frequent snapshot updates. HTML-fragment and enriched-result caches reduce repeated pagination work; a short TTL bounds price-driven membership changes that a structural counter alone could miss. On the client, new-update behavior and persisted interface preferences aim to avoid destroying a user's place while they inspect a row. These optimizations belong to the current collaborative system, not automatically to Joey's personal commit list.

History charts combine Business, consumer and BSR series, timeframe controls, activation bands and missing-data presentation. Past Deals distinguishes end time and duration from the last observation. The chart endpoint returns an explicit empty state instead of a silent missing fragment for a never-fetched item. This makes temporal state legible: no price, an old price and no active deal should not all look like a blank cell.

Past-deal presentation with ended/duration and previous-versus-current price information.
Past-deal presentation with ended/duration and previous-versus-current price information.
Server-side product-title search returning a synthetic caliper record.
Server-side product-title search returning a synthetic caliper record.
Advanced filter drawer with discount, rank, demand, history and catalog facets; no redesign substituted for the application.
Advanced filter drawer with discount, rank, demand, history and catalog facets; no redesign substituted for the application.
Current grouped settings layout over synthetic/local configuration.
Current grouped settings layout over synthetic/local configuration.
A2A interface at 390px, using synthetic catalog and prices.
A2A interface at 390px, using synthetic catalog and prices.

The retired cross-retailer system is still a substantial learning chapter

Off-Amazon work expanded the project into browser integration, product identity and extraction fallbacks. Earlier versions included a product-centric comparison table, watch health, selector capture and sourcing workflows. The extension extracted identity from an already open Amazon page, then used retailer adapters and streamed results into its panel. Identity included normalized GTINs, brand/model clues and optional image evidence. It was designed to avoid making new Amazon fetches from the browser integration; client code used deterministic matching rather than embedding a hosted model API key.

The matching pipeline is especially concrete. Exact GTIN identity can short-circuit. Otherwise it extracts attributes, records contradictions, computes weighted title/model/brand signals, optionally uses perceptual image hashes and selects a category-dependent weighting profile. Available signals are renormalized so a missing image does not automatically punish a candidate. Attribute-confirmation bonuses and model/pack penalties add explainable detail. Rejection and numeric similarity remain separate outputs. Running the original historical modules offline gives an exact synthetic match a score of 1, strongly demotes a mismatched model/pack example and gives an unrelated item zero; this is an illustrative fixture, not a benchmark of retailer accuracy.

Price extraction also used ordered fallbacks: structured JSON-LD, a captured signal bundle and a site selector library; fetch strategies included retailer JSON paths, AMP and direct browser handling. Health distinctions separate selector rot from temporary blocking, while host circuit breakers, retry ownership and drift records make failures inspectable. These capabilities were removed on July 28, with the extension itself retired in September. The recovered screenshots are explicitly historical renderers with synthetic inputs, not resurrected production services or claims of current coverage.

Recovered original off-Amazon comparison template from cc0b807^ with synthetic retailer data.
Recovered original off-Amazon comparison template from cc0b807^ with synthetic retailer data.
Recovered original extension renderer from cc0b807^, populated with synthetic product state.
Recovered original extension renderer from cc0b807^, populated with synthetic product state.

The preserved edges are part of the story

The most useful lessons are often the unresolved edges. A September note identifies that the fixed four-slot bulk ladder can discard later quantity rungs. The source still slices that ladder, and the note explicitly parks the issue rather than claiming it fixed. Another note says a gate-check dwell change is built but its live run is parked. The presence of code, a passing local scenario and an operational rollout are separate states. The project should therefore appear as an evolving collaborative tool with retired branches and unfinished fixes, not a polished feature checklist assembled from its oldest README.

My work spans the initial project, sourcing workflows, interface design, ownership filtering, freshness guards and live alert presentation. The project brought together precise price arithmetic, database design, concurrency, event logs and a dense dashboard. One recurring lesson: a useful comparison needs to explain where a price came from and whether it is still current.

Project source ↗