Serverless · Freelance

Shopify Product Recommendations with Amazon Personalize, Lambda and SAM

A serverless integration that streams Shopify webhooks into Amazon Personalize and serves recommendations through API Gateway and Lambda, all defined in an AWS SAM template.

  • AWS SAM
  • Lambda
  • API Gateway
  • DynamoDB
  • Amazon Personalize
  • CloudFormation
  • Shopify Webhooks
  • Python

// Why this matters

Shopify product recommendations with Amazon Personalize are attractive to small merchants because the alternative is either a third-party app with a monthly fee that scales with revenue, or a hand-rolled "customers also bought" query that stops being useful after a few hundred products. Personalize gives you a managed collaborative-filtering model, and you pay for training hours and requests rather than seats.

The engineering motivation is the same one that drives most small serverless builds: traffic from a shop is spiky and mostly idle. A webhook consumer and a read API that scale to zero are a better fit than an always-on service that someone has to patch. SAM keeps the whole thing in one reviewable file.

// The problem

Shopify can tell you what happened in a store through webhooks, and it can give you history through the Admin API, but it will not train a model for you. Out of the box you have two data sources with different shapes: a push stream of events that can arrive twice, out of order, or not at all, and a paginated REST history that returns at most a page of orders per call and hands you the next page as a Link header.

On the AWS side, Personalize is picky. It wants an interactions dataset with a user id, an item id and a timestamp in a precise schema, it needs a minimum amount of data before training succeeds, and it cannot be queried until a campaign is live. If you skip the intermediate store you end up debugging Personalize import failures with no way to replay the data.

There is also a trust problem. A public webhook endpoint accepts anything a stranger posts to it. Without signature verification, anyone who finds the URL can poison your training data.

// The solution

The design has three loops. The ingest loop receives webhooks, verifies them and writes to DynamoDB. The training loop exports DynamoDB to S3 on a schedule and triggers a Personalize dataset import and solution version. The serving loop is a read-only API that calls a campaign and joins the returned item ids with product titles and images.

DynamoDB sits in the middle on purpose. It gives us idempotent writes (the order line id is the key, so a duplicate delivery is harmless), a replayable history, and a place to backfill from the Admin API when the shop already has years of orders. I considered sending events straight to the Personalize event tracker, and we still can for real-time signals, but training needs a historical import anyway, so the table is the source of truth.

Shopify credentials never go in the template. The Admin API token lives in Secrets Manager, and each Lambda reads it once per container start. The webhook signing secret is stored the same way. The SAM template only holds the ARNs and the IAM permissions to read them.

For backfill we page through the orders endpoint following the rel="next" link until it is exhausted, which is easy to get wrong if you parse the header with string slicing, so use a proper link parser. I rejected Step Functions for orchestration: the flow is linear and a scheduled Lambda is enough.

How it flows flow1. Shopify → 2. HMAC gate → 3. Ingest Lambda → 4. Stream → 5. Scheduled export → 6. Solution → 7. API Gateway → 8. Read Lambda → 9. Storefront01Shopify02 · GATEHMAC gate03Ingest Lambda04Stream05Scheduled export06Solution07API Gateway08Read Lambda09Storefront
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Shopifyorder and product webhooks fire on every change
  2. HMAC gate gateLambda rejects any payload with a bad signature
  3. Ingest Lambdanormalises the payload and writes it to DynamoDB
  4. StreamDynamoDB stream forwards new interactions to Personalize event tracker
  5. Scheduled exportnightly job writes the dataset to S3 and starts an import job
  6. SolutionPersonalize trains a recommender on the imported data
  7. API Gatewaystorefront calls GET /recommendations?email=...
  8. Read Lambdaasks the campaign for items, enriches them with product data
  9. Storefrontrenders the list on the product or cart page
ShopifyAPI GatewayIngest LambdaDynamoDBPersonalizePOST orders/create with HMAC headerproxy event401 if the signature is invalidPutItem order line (conditional)nightly export and dataset importcampaign serves GetRecommendations
Webhook to recommendation. Ingest and serve paths share only the DynamoDB table.
EdgeShopify webhooksStorefront JSAPIAPI Gateway RESTThrottlingAPI keyComputeIngest LambdaExport LambdaRecommend LambdaDataDynamoDB ordersS3 export bucketPersonalize datasetSecretsSecrets ManagerIAM least privilege
Stack layout. One SAM template owns every layer.

// Before you start

  • An AWS account with permission to create IAM roles, Lambda, API Gateway, DynamoDB, S3 and Personalize resources
  • AWS SAM CLI 1.100 or newer and Python 3.12
  • A Shopify store with a custom app that has read_orders and read_products scopes
  • The app signing secret and Admin API token stored in AWS Secrets Manager as <shopify-secret-name>
  • At least a few thousand historical interactions (or a plan to backfill) before the first training run

// Step-by-step implementation

  1. 01 Define the SAM template skeleton

    Start with the template because everything else hangs off it. We declare the table, the three functions and the API in one file. The table key is the order line id so retries are idempotent, and the stream is enabled in case you later want real-time event tracking.

    Keep parameters for the things that change per store: the secret names and the Personalize campaign ARN. Everything else is derived.

  2. 02 Verify the Shopify webhook before trusting it

    Shopify signs the raw request body with HMAC-SHA256 and sends the base64 result in X-Shopify-Hmac-Sha256. You must hash the exact bytes you received. If API Gateway base64-encodes the body for you, decode it first, otherwise the signature will never match and you will spend an afternoon blaming Shopify.

    Use hmac.compare_digest rather than == so the check is constant time, and return 401 before touching DynamoDB.

  3. 03 Register the webhooks from code

    Clicking webhooks together in the admin UI works once and then nobody remembers how it was configured. Register them through the Admin API in a small bootstrap script so the subscription is reproducible and points at the API Gateway URL from the stack outputs.

    Run it after every deploy; Shopify returns 422 for an address that already exists, which the script treats as success.

  4. 04 Backfill order history with proper pagination

    Personalize needs history, and webhooks only tell you about the future. The Admin API returns orders in pages and puts the next page URL in the Link response header. Parse it with the requests link helper instead of slicing strings; header formats include both next and previous links and the order is not guaranteed.

    Write through the same DynamoDB key as the webhook path, so running the backfill twice is harmless.

  5. 05 Export to S3 and import into Personalize

    Personalize reads from S3 in a CSV with the header USER_ID,ITEM_ID,TIMESTAMP and timestamps as Unix seconds. A scheduled Lambda scans the table, writes the CSV and starts a dataset import job. The scan is fine at shop scale; if you ever have millions of rows use a DynamoDB export to S3 instead.

    Create the dataset group, schema and dataset once, outside the stack, because Personalize resources are slow to delete and you do not want a stack rollback to take your trained solution with it.

  6. 06 Train a solution and publish a campaign

    Training is a one-off CLI sequence plus a periodic retrain. Use the user-personalization recipe for per-shopper lists, or similar-items for a product page widget. The campaign is what the read Lambda calls, and it bills per provisioned transaction per second, so start at the minimum.

    After each retrain you create a new solution version and update the campaign to point at it. Automate that in the export Lambda once you trust the data.

  7. 07 Serve recommendations through API Gateway

    The storefront should never hold AWS credentials. It calls a small GET endpoint with the shopper email, the Lambda asks the campaign for item ids, and then looks up titles and images so the browser gets everything in one response.

    Cache the product lookup in the container; product data changes far less often than recommendations. Return an empty list rather than an error when the shopper is unknown, so the page can fall back to bestsellers.

  8. 08 Deploy and wire up the storefront

    Deploy with a guided first run, then non-interactively from CI. Save the outputs: the webhook URL feeds the registration script and the recommendations URL goes into the theme.

    Keep one samconfig per environment. A staging stack against a development store lets you replay webhooks without touching real customers.

// How to verify it works

  • Post a webhook with a wrong signature using curl and confirm a 401 and no new DynamoDB item.
  • Create a test order in the development store and confirm one item per line appears in the table within seconds.
  • Run aws personalize describe-dataset-import-job and confirm status ACTIVE after the export Lambda runs.
  • Call the recommendations endpoint with a known email and confirm eight item ids; with an unknown email confirm an empty list and HTTP 200.
  • Run the backfill twice and confirm the item count in the table does not change on the second run.

// Design decisions and trade-offs

  • Verify every Shopify webhook with its HMAC signature before doing any work
  • Keep the Shopify admin token in Secrets Manager and cache it per Lambda container
  • Store the order history in DynamoDB first, then export to Personalize on a schedule
  • Return recommendations from a thin read-only Lambda so the storefront never talks to Personalize directly
  • Define everything in one SAM template so a second shop is a stack parameter, not a rewrite

// Pitfalls and lessons learned

  • Hashing the parsed JSON instead of the raw body breaks signature checks; whitespace and key order change the digest.
  • API Gateway may deliver the body base64-encoded; check isBase64Encoded before computing the HMAC.
  • Personalize import fails with an unhelpful message when timestamps are ISO strings instead of Unix seconds.
  • A campaign left running at higher throughput than needed is the main source of surprise cost; keep min TPS at 1.
  • Parsing the Link header with regular expressions breaks when the response contains both next and previous links.
  • Deleting the stack removes the table. Export or enable point-in-time recovery before you experiment with updates.
  • Anonymous orders collapse into one fake user and distort recommendations; filter them out of the export.

// Frequently asked questions

How do I add product recommendations to Shopify with Amazon Personalize?

Collect order interactions through webhooks and an Admin API backfill, import them into a Personalize dataset, train a user-personalization solution, publish a campaign and call it from a small API behind API Gateway.

Do I need Personalize event tracker as well?

Not to start. Batch import from order history is enough for a first model. Add the event tracker later if you want views and add-to-cart signals to influence results in real time.

How much data does Personalize need?

The service enforces a minimum number of interactions and distinct users before it will train. Backfilling history is the fastest way to reach it; small stores may need a similar-items recipe instead.

Why store orders in DynamoDB instead of sending them straight to Personalize?

Training needs a historical import, and a table gives you idempotent writes, replay and an easy backfill. It also decouples ingest from the training schedule.

Can the same template serve several shops?

Yes. Deploy it as separate stacks with different secret names and campaigns; nothing in the code is shop specific.

// The outcome

The shop gets a recommendations endpoint that costs nothing when idle, and onboarding another store means deploying the same template with different parameters. Recommendation quality depends on how much order history exists, which is the first thing to check when results look generic.

// Where to take it next

// Keep reading