Home / Blog / Amazon Buy Box Price Monitoring with AWS CloudWatch Custom Metrics

Amazon Buy Box Price Monitoring with AWS CloudWatch Custom Metrics

Push Amazon Buy Box price, availability and offer-count metrics from the SellerMagnet API to AWS CloudWatch as custom metrics via PutMetricData, using boto3. sellermagnet.py / retry.py need zero changes from the Python quickstart. The real trap: PutMetricData validates the ENTIRE request as one unit, so a single stale timestamp or out-of-range value anywhere in the batch can fail every other tracked ASIN's metrics too.

November 28, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal showing a Python price-watch script pushing Amazon Buy Box metrics to AWS CloudWatch

To monitor an Amazon Buy Box price in AWS CloudWatch, run a small Python script on a schedule that calls the SellerMagnet API, builds a CloudWatch MetricData list, and calls boto3's put_metric_data. The SellerMagnet client code is the unmodified Python quickstart's sellermagnet.py and retry.py. The part worth getting right on purpose: PutMetricData validates the whole request body as one unit, and a point's timestamp has to sit inside a documented window or the entire call is rejected.

Key Takeaways

  • PutMetricData validates the ENTIRE request body as one unit (AWS's own API reference): one bad value anywhere fails the whole call and nothing is ingested, so this script builds one MetricData list per run covering every ASIN and sends exactly one call, never one call per ASIN.
  • A point's timestamp must sit within 2 weeks in the past or 2 hours in the future of now; this script checks every point against that window itself right before the push, using each ASIN's own fetch time, and drops only the stale ones instead of risking the whole batch.
  • boto3 (AWS's own SDK) handles the SigV4 request signing; CloudWatch's auth is not a simple API-key header like most other vendor-metrics APIs in this series.
  • Throttling and InternalServiceError are retried with backoff; InvalidParameterValue, MissingParameter and AccessDenied are real input/permission problems and are raised at once, never retried.
  • A real $0.00 Buy Box price is still pushed as a genuine zero (buybox_available=1, buybox_price_cents=0); only a response with no Buy Box at all skips the price series.

Why build one CloudWatch call for the whole batch instead of one call per ASIN?

AWS's own PutMetricData reference says plainly that an invalid parameter value anywhere in the request fails the entire call. There is no documented per-point partial success, unlike CloudWatch Logs' PutLogEvents. Calling PutMetricData once per ASIN would only add N chances to hit a transient AWS-side error and end up with half the watch list updated and half stale; one call carrying every ASIN's metrics either lands as a whole or fails as a whole, which is easier to reason about and to alarm on.

Install requests + boto3 and set the credentials

python3 -m venv .venv
.venv/bin/pip install requests boto3
export SELLERMAGNET_API_KEY="your-key-here"
export AWS_ACCESS_KEY_ID="your-aws-key-id"
export AWS_SECRET_ACCESS_KEY="your-aws-secret"

What does the exporter script actually push?

For every ASIN it calls /amazon-product-offers through the quickstart's retry logic, then builds up to four metrics per ASIN: the Buy Box price in cents, an availability flag, an FBA flag and the first-page offer count, each carrying asin and marketplace dimensions. A fifth metric, the run's own last-success timestamp, is always added once per run. Every datum uses Unit: "None" - CloudWatch has no built-in currency unit, so the cents live in the metric name instead.

sellermagnet.py - unmodified from the Python quickstart

import os

import requests

API = "https://sellermagnet-api.com/api"


class ApiError(Exception):
    def __init__(self, status: int, message: str, retry_after: float = 0.0):
        super().__init__(f"{status}: {message}")
        self.status, self.retry_after = status, retry_after


def new_session() -> requests.Session:
    session = requests.Session()
    session.headers["X-Api-Key"] = os.environ["SELLERMAGNET_API_KEY"]
    return session


def get(session: requests.Session, endpoint: str, **params) -> dict:
    resp = session.get(f"{API}/{endpoint}", params=params, timeout=120)
    try:
        body = resp.json()
    except ValueError:                      # e.g. an HTML page from a proxy
        body = {}
    if resp.status_code == 200 and body.get("success"):
        return body["data"]
    try:
        wait = float(resp.headers.get("Retry-After", 0))
    except ValueError:
        wait = 0.0
    raise ApiError(resp.status_code, body.get("message", "request failed"), wait)

retry.py - unmodified from the Python quickstart

import random
import time

import requests

from sellermagnet import ApiError, get

RETRYABLE = {429, 500, 502, 503}


def get_with_retry(session, endpoint: str, attempts: int = 4, **params) -> dict:
    internal_errors = 0
    for attempt in range(1, attempts + 1):
        try:
            return get(session, endpoint, **params)
        except ApiError as err:
            internal_errors += err.status == 500
            if err.status not in RETRYABLE or attempt == attempts or internal_errors > 1:
                raise                      # a second 500 in a row: report it, don't loop
            backoff = min(2 ** attempt, 30) + random.uniform(0, 1)
            time.sleep(max(backoff, err.retry_after))
        except (requests.ConnectionError, requests.Timeout):
            if attempt == attempts:
                raise
            time.sleep(min(2 ** attempt, 30))

Trimmed /amazon-product-offers response (example values)

{
  "success": true,
  "data": {
    "asin": "B0CL61F39H",
    "marketplaceId": "ATVPDKIKX0DER",
    "buyBox": {"sellerId": "Amazon", "totalPrice": 444.99, "fulfillmentType": "FBA"},
    "offers": [
      {"sellerId": "Amazon", "totalPrice": 444.99, "fulfillmentType": "FBA"},
      {"sellerId": "acme-llc", "totalPrice": 459.00, "fulfillmentType": "FBM"}
    ]
  }
}

cw_pricewatch.py - builds and pushes one CloudWatch PutMetricData call per run

"""Push Amazon Buy Box price/availability metrics from the SellerMagnet API to Amazon CloudWatch
as custom metrics via PutMetricData.

Reuses sellermagnet.py / retry.py from the Python quickstart unchanged. Example:

    session = new_session()
    watch(session, asins, marketplace_id, cw_client=boto3.client("cloudwatch", region_name="us-east-1"))
"""
import time

from botocore.exceptions import ClientError

from retry import get_with_retry
from sellermagnet import ApiError, new_session

NAMESPACE = "SellerMagnet/BuyBox"
MAX_PAST_S = 14 * 24 * 3600       # PutMetricData rejects a point more than 2 WEEKS in the past
MAX_FUTURE_S = 2 * 3600           # or more than 2 HOURS in the future (looser than Datadog's 1h/10min)
MAX_METRICS_PER_CALL = 1000       # PutMetricData hard cap, MetricData + EntityMetricData combined
RETRYABLE_CODES = {"Throttling", "ThrottlingException", "RequestLimitExceeded", "InternalServiceError"}


def _datum(metric: str, ts: int, value: float, dims: list[dict]) -> dict:
    return {
        "MetricName": metric,
        "Dimensions": dims,
        "Timestamp": ts,          # epoch seconds; botocore also accepts a datetime, both work
        "Value": float(value),
        "Unit": "None",           # CloudWatch has no currency unit; cents live in the metric name
    }


def _in_window(ts: int, now: int) -> bool:
    return (now - ts) <= MAX_PAST_S and (ts - now) <= MAX_FUTURE_S


def _push_with_retry(cw_client, metric_data: list[dict], attempts: int = 4) -> None:
    """One PutMetricData call for the WHOLE batch. The API validates the entire request body as
    one unit (AWS's own PutMetricData docs: an invalid value anywhere fails the whole call and
    ingests nothing), so this never splits into one call per ASIN. A retryable AWS-side error
    (Throttling / InternalServiceError, both in botocore's own standard retry list) backs off and
    tries again; a client error (InvalidParameterValue, MissingParameter, AccessDenied) is a real
    input/permissions problem and must not be retried."""
    for attempt in range(1, attempts + 1):
        try:
            cw_client.put_metric_data(Namespace=NAMESPACE, MetricData=metric_data)
            return
        except ClientError as err:
            code = err.response.get("Error", {}).get("Code", "")
            if code not in RETRYABLE_CODES or attempt == attempts:
                raise
            time.sleep(min(2 ** attempt, 30))


def watch(session, asins: list[str], marketplace_id: str, cw_client, clock=time.time) -> dict:
    """Fetch every ASIN's offers, build ONE CloudWatch MetricData list for the whole batch and
    push it in a SINGLE PutMetricData call. Each ASIN's own fetch timestamp is captured when its
    data arrives (a slow SellerMagnet retry backoff can legitimately push one ASIN's captured
    time well behind the others), then checked against the documented +2h/-2weeks window at the
    moment the batch is actually about to be sent -- a stale point here would fail the WHOLE
    PutMetricData call and ingest nothing for every other ASIN too, so this script drops only the
    stale ones itself instead of risking the batch on AWS's own validation."""
    pending: list[dict] = []
    report = {"available": {}, "unavailable": {}, "dropped_stale": []}
    for asin in asins:
        dims = [{"Name": "asin", "Value": asin}, {"Name": "marketplace", "Value": marketplace_id}]
        try:
            data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=marketplace_id)
        except ApiError as err:
            if err.status in (401, 403):
                raise                      # key/credits problem: stop before any CloudWatch push
            report["unavailable"][asin] = err.status
            continue
        ts = int(clock())                  # captured now; may be stale by the time we actually push
        buybox = data.get("buyBox")
        if not buybox:
            pending.append({"ts": ts, "dims": dims, "asin": asin, "points": [("buybox_available", 0)]})
            report["available"][asin] = False
            continue
        price_cents = round(float(buybox["totalPrice"]) * 100)
        is_fba = 1 if buybox.get("fulfillmentType") == "FBA" else 0
        offer_count = len(data.get("offers") or [])
        pending.append({"ts": ts, "dims": dims, "asin": asin, "points": [
            ("buybox_price_cents", price_cents), ("buybox_available", 1),
            ("buybox_is_fba", is_fba), ("offers_count", offer_count),
        ]})
        report["available"][asin] = True

    send_ts = int(clock())                 # the moment the batch is actually about to be sent
    metric_data: list[dict] = []
    for item in pending:
        if not _in_window(item["ts"], send_ts):
            report["dropped_stale"].append(item["asin"])
            continue
        for name, value in item["points"]:
            metric_data.append(_datum(name, item["ts"], value, item["dims"]))
    metric_data.append(_datum("last_run_unixtime", send_ts, send_ts, [{"Name": "marketplace", "Value": marketplace_id}]))

    assert len(metric_data) <= MAX_METRICS_PER_CALL, "batch too large for one PutMetricData call"
    _push_with_retry(cw_client, metric_data)
    report["metrics_pushed"] = len(metric_data)
    report["calls"] = 1
    return report


if __name__ == "__main__":
    import boto3
    watch(new_session(), ["B0CL61F39H"], "ATVPDKIKX0DER", boto3.client("cloudwatch", region_name="us-east-1"))
Flow diagram from the price-watch script through the SellerMagnet API to one CloudWatch PutMetricData call
Every ASIN's metrics are gathered first; CloudWatch sees exactly one call per run, not one per ASIN.

Which SellerMagnet errors should stop the run versus just one ASIN?

A 401 or 403 means the key or the credit balance is the problem, not any one ASIN, so the whole run raises before anything is pushed to CloudWatch at all. Every other error (a billed 404, or 502/503 exhausted after the retry cap) marks only that ASIN unavailable and the batch carries on, the same convention as every other price-watch post in this series.

SellerMagnet API status codes, billing and this script's reaction.
StatusMeaningBilledReaction
200SuccessYesUse data
401 / 403Key or creditsNoStop the whole run before any CloudWatch push
404ASIN not on this marketplaceYesASIN marked unavailable, batch continues
429Concurrency capNoWait Retry-After, retried
500Internal errorNo, refundedRetry once
502 / 503Upstream / breakerYesWait, then retry, capped at 4, then ASIN marked unavailable

Which CloudWatch errors are worth retrying?

boto3 raises a botocore.exceptions.ClientError carrying an AWS error code in err.response["Error"]["Code"]. Throttling and InternalServiceError are the AWS-side failures worth a backoff and a retry; InvalidParameterValue, MissingParameter and AccessDenied point at a real problem in the request or the IAM permissions, and retrying them just repeats the same rejection.

Table of CloudWatch PutMetricData error codes and whether this script retries each one
Only the two AWS-side failure codes get a retry; every client/permission error is raised at once.

One stale timestamp can sink the whole batch

CloudWatch rejects a point more than 2 weeks in the past or more than 2 hours in the future, and PutMetricData validates the whole request body as one unit, with no documented per-point partial success. A long SellerMagnet retry backoff inside one run can legitimately push one ASIN's captured timestamp toward that edge by the time the batch finally sends - check every point against the window yourself before building the request, and drop only the stale ones, rather than risk every other ASIN's fresh metrics on one slow retry.

What does the CloudWatch dashboard side look like?

A CloudWatch dashboard widget on the SellerMagnet/BuyBox namespace, metric buybox_price_cents with dimension asin:B0CL61F39H, plots the price directly from the pushed metric (divide by 100 for dollars in the widget's math expression). A CloudWatch alarm comparing the current value against a threshold, or against itself one period ago, needs no extra storage in the script at all - CloudWatch already has the history once the points are in. Setting up that alarm is a one-time console/CLI step (PutMetricAlarm), separate from this script.

Real output from the tested harness (fakehttp.py faking requests.Session.get, botocore's Stubber faking PutMetricData; no real CloudWatch or SellerMagnet calls)

PASS 1 happy path: 1 CloudWatch call
PASS 1 happy path: 5 metrics pushed (4 buybox + last_run)
PASS 1 happy path: available true
PASS 1 happy path: no dropped-stale points
PASS 2 no buybox: available false
PASS 2 no buybox: only 2 metrics (buybox_available=0 + last_run)
PASS 3 fbm: is_fba metric value is 0
PASS 4 zero price: price_cents series present with value 0
PASS 4 zero price: available true (a real $0 offer is not 'no offer')
PASS 5 404: single CloudWatch call for the 2-ASIN batch
PASS 5 404: gone ASIN marked unavailable
PASS 5 404: sibling ASIN still fully recorded
PASS 6 401 aborts: raised ApiError(401)
PASS 6 401 aborts: zero CloudWatch calls made
PASS 7 429-then-ok: 2 SellerMagnet attempts
PASS 7 429-then-ok: final price recorded
PASS 8 cw throttling: 2 CloudWatch attempts, final push succeeds
PASS 9 cw InvalidParameterValue: raised without retry
PASS 10 stale timestamp: B0STALE dropped before the push
PASS 10 stale timestamp: B0FRESH still pushed in the SAME single call
PASS 10 stale timestamp: B0STALE never reached CloudWatch
PASS 10 stale timestamp: still exactly 1 CloudWatch call total
PASS 11 empty batch: last_run_unixtime still pushed
PASS 11 empty batch: still exactly 1 CloudWatch call
PASS 12 5-asin batch: exactly 1 CloudWatch call, never 1-per-asin
PASS 12 5-asin batch: all 5 ASINs' available series present
PASS 13 oversized batch: refused before any CloudWatch call (260 asins * 4 metrics > 1000)
PASS 13 oversized batch: zero CloudWatch calls made

28 assertions passed

Frequently Asked Questions

Does a bad value from one ASIN fail every other ASIN's metrics too?

Yes, if it reaches CloudWatch. PutMetricData validates the whole request body as one unit: AWS's own API reference says an invalid value anywhere fails the entire call and nothing is ingested. This script pushes every ASIN's metrics in one PutMetricData call per run, so it checks each point's own age against CloudWatch's window itself and drops only the stale ones before building that call, rather than risk the whole batch on AWS's own validation.

Why boto3 instead of a raw HTTP POST like some other vendor-metrics posts in this series?

CloudWatch's PutMetricData is a SigV4-signed AWS API, not a simple API-key header. boto3 is AWS's own SDK and handles the request signing; hand-rolling SigV4 adds a real source of silent bugs (a wrong signature is just another 403) for no benefit over the officially supported client.

How old can a metric timestamp be before CloudWatch rejects it?

Up to 2 weeks in the past or 2 hours in the future, per AWS's PutMetricData reference. That is a much looser window than some other monitoring vendors' metrics intake, but still tight enough that a long SellerMagnet retry backoff inside one run can let an early ASIN's captured timestamp drift toward the edge by the time the batch is actually sent.

Is a real $0.00 Buy Box price sent as a missing value?

No. buybox_available is pushed as 1 and buybox_price_cents as 0, so a CloudWatch graph shows a genuine zero. Only a response with no Buy Box at all (no featured offer) skips the price series and pushes buybox_available as 0 instead.

Does CloudWatch rate-limit PutMetricData the same way SellerMagnet rate-limits its own API?

Both can throttle, but differently. CloudWatch returns a retryable Throttling error under sustained high request rates; SellerMagnet's own 429 is a free-tier concurrency cap on the /amazon-product-offers calls. This script retries each independently, on its own side.

Bottom line: build one CloudWatch PutMetricData call per run covering every tracked ASIN, use Unit: "None" with the cents in the metric name, and check each point's timestamp against CloudWatch's own +2h/-2weeks window before it is ever sent. The retry and error-handling pattern underneath is identical to the Python quickstart; the rate limits and error handling guide covers the concurrency cap this script's retry policy respects. Every endpoint is on the API documentation page, and a free account includes 150 credits to try it.

Related Articles

Continue exploring topics related to this article.

Terminal window showing the Amazon Buy Box lost alert a Python script sent through Threema Gateway
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Threema: a Bare Message ID, Not JSON

Get an Amazon Buy Box lost alert sent through Threema Gateway: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm on a second check and POST one form-encoded message per run to send_simple. A successful send answers HTTP 200 with the new message's id as bare plain text, no JSON, while every failure gets its own HTTP status. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script sent via WeCom
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in WeCom: Read errcode, Not HTTP Status

Get an Amazon Buy Box lost alert pushed to WeCom (Enterprise WeChat): poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one markdown message per run to a group robot webhook. WeCom always answers HTTP 200; the script reads the errcode field inside the JSON body instead, and caps the message on UTF-8 bytes, not characters. Costs one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted to Chatwork
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Chatwork: Form Body, Not JSON

Get an Amazon Buy Box lost alert posted straight into Chatwork: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one message per run through Chatwork's Add Message endpoint. Covers the X-ChatWorkToken header auth, the form-urlencoded body other channels get wrong by sending JSON, and the two separate 429 rate limiters. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime