Serverless · Freelance

Event-Driven Business Workflows: Shopify Webhooks, Stripe and SQS on Lambda

Webhook receivers, payment events and queue-backed workers on Lambda, plus an email proxy that routes supplier mail by body content, tested locally against ElasticMQ.

  • AWS Lambda
  • API Gateway
  • Amazon SQS
  • ElasticMQ
  • Amazon SES
  • Shopify webhooks
  • Stripe
  • Python
  • pytest

// Why this matters

Reliable shopify webhook aws lambda processing is a requirement for any shop that does more than display products. Orders, refunds, inventory changes and payment confirmations all arrive as HTTP callbacks, and the sender expects a fast answer. If your endpoint is slow, throws, or is briefly down, the sender retries on its own schedule, and eventually disables the webhook.

Business workflows built on these events also tend to grow side effects: notify the supplier, send a receipt, update a spreadsheet, tag the customer. If all of that runs inside the request, one slow dependency makes the entire webhook fail, and a retry then repeats the parts that already succeeded.

The fix is a pattern, not a product: accept, verify, enqueue, and process asynchronously with idempotent workers. I applied it to Shopify storefronts, Stripe payment flows and an email proxy for a supplier-ordering process.

// The problem

Synchronous handlers fail in ways that are hard to see. A Stripe webhook that takes longer than its timeout is retried, so a payment confirmation can be processed twice and send two receipts. A Shopify burst during a sale means dozens of simultaneous invocations all hammering the same downstream API, which then rate-limits and fails more of them.

Testing is the second pain. Queue-based code is awkward to unit test when the only queue is a managed cloud service, so developers skip tests or mock so heavily that the tests prove nothing. Bugs then appear only in production with real traffic.

The email side adds its own problem. Suppliers reply to a shared mailbox and each message needs to reach the right internal owner, but the only signal is the body text: an order number, a keyword, a product family. Hard-coding that logic means a deployment for every new supplier or phrase.

// The solution

The architecture has three Lambdas and one queue per flow. The receiver sits behind API Gateway. It reads the raw request body (important for signature checks), verifies the provider signature with HMAC-SHA256 and a shared signing key from the secrets store, writes a message to SQS containing the topic, event ID and payload, and returns 200. It does nothing else, so it is fast and almost never fails.

The worker is subscribed to the queue with an event source mapping. SQS delivers batches, and the worker handles each record independently. Before acting it checks whether the event ID has been processed, using a small table with a conditional write: if the put fails because the key exists, the event is a duplicate and is skipped. This makes at-least-once delivery safe.

Failure handling is configured, not coded. The queue has a visibility timeout longer than the worker timeout, and a redrive policy that moves a message to a dead-letter queue after a few receives. A batch item failure response lets one bad record fail without re-driving the whole batch.

For local work, ElasticMQ runs as a single container and implements the SQS API. The code takes an optional endpoint URL from the environment, so tests point boto3 at the container and production leaves it unset. The tests create a queue, call the receiver function with a signed fixture, then run the worker and assert on the outcome.

The email proxy follows the same shape. SES receives the message and drops it into S3 or invokes Lambda; the function parses the body and evaluates an ordered list of rules (a pattern and a destination). The first match decides the forwarding address, and unmatched mail goes to a catch-all. Alternatives I rejected were Step Functions for every flow (more machinery than these linear jobs need) and processing inline (the failure modes above). For another queue-driven example see Event-driven Call-Recording Transcoding and Transcription.

How it flows flow1. Webhook arrives → 2. Verify signature → 3. Enqueue → 4. Worker poll → 5. Idempotency check → 6. Business action → 7. Retry → 8. Dead-letter01Webhook arrives02 · GATEVerify signature03Enqueue04Worker poll05Idempotency check06Business action07Retry08Dead-letter
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. Webhook arrivesShopify or Stripe posts to an API Gateway endpoint
  2. Verify signature gateHMAC of the raw body is compared before anything else
  3. Enqueuereceiver writes the event to SQS and returns 200 fast
  4. Worker polla Lambda consumes batches from the queue
  5. Idempotency checkevent ID looked up in a store to skip duplicates
  6. Business actionupdate order, record payment, or send an email
  7. Retryfailures return to the queue after the visibility timeout
  8. Dead-letterafter N attempts the message is parked for inspection
ProviderReceiverSQSWorkerStorePOST event + signaturesend message after HMAC ok200 immediatelydeliver batchconditional put event iddelete on success
Webhook to worker. The receiver returns fast; the worker does the slow, retryable work.
IngestAPI GatewayReceiver LambdaHMAC verificationBufferMain queueDead-letter queueVisibility timeoutProcessWorker LambdaIdempotency tableSES mail proxyObserveCloudWatch alarmsDLQ depth metricStructured logs
Layers of the workflow platform. Ingest, buffer, process, and observe are separate concerns.

// Before you start

  • AWS account with rights for Lambda, API Gateway, SQS, SES and IAM
  • Python 3.12, boto3, pytest and Docker for running ElasticMQ locally
  • A Shopify development store or a Stripe test-mode account to produce sample events
  • A verified SES sender or domain in <region> for the email part
  • A secrets store (Secrets Manager or Parameter Store) for the signing keys, referred to as <vault-path>

// Step-by-step implementation

  1. 01 Run ElasticMQ locally and create the queues

    Start with the local broker so you can build and test without AWS. ElasticMQ listens on a single port and accepts the same API calls as SQS. Create a main queue and a dead-letter queue, then attach a redrive policy to the main one.

    Using a helper that reads an optional endpoint from the environment is the key trick; the same function works in tests and in production.

  2. 02 Write the signature-verifying receiver

    Signature checks must run over the raw bytes exactly as received. If you parse the JSON first and re-serialise it, the digest changes and every valid event is rejected. Shopify sends a base64 HMAC in a header; Stripe sends a timestamped signature you recompute from the timestamp and body.

    Compare digests with a constant-time function and reject anything that fails with 401 before touching the payload.

  3. 03 Make the worker idempotent

    Providers deliver at least once, and SQS does too. A conditional put with attribute_not_exists is the cheapest idempotency gate: it succeeds the first time and raises the second. Store a TTL so the table does not grow forever.

    Return partial batch failures so one poisoned record does not cause the others to be reprocessed.

  4. 04 Wire the queue to the worker with a redrive policy

    In AWS, an event source mapping connects the queue to the worker. Set a modest batch size, enable partial batch responses, and make sure the queue visibility timeout is at least six times the function timeout; this is AWS guidance and avoids duplicate processing while a batch is running.

    The dead-letter queue should have its own alarm, since a non-empty DLQ means real business events are stuck.

  5. 05 Handle Stripe payment events the same way

    Stripe differs only in the signature scheme. The header carries a timestamp and one or more signatures; you recompute HMAC over the timestamp, a dot and the raw body, then compare. Reject timestamps older than a few minutes to stop replay.

    Everything after verification is identical: enqueue, then process idempotently, keyed by the Stripe event ID.

  6. 06 Route supplier emails by body content

    Receive mail through SES into a Lambda action or S3 plus a trigger. Parse the plain-text part, then run an ordered rule list. Each rule is a regular expression and a destination; the first match wins and a default rule catches the rest.

    Keep the rules in a JSON file or table so a new supplier is a data change. Forward with SES SendRawEmail, preserving the original body, and set a header so you never loop mail back into the proxy.

  7. 07 Test the whole flow with pytest on ElasticMQ

    The test builds a signed fixture, calls the receiver, reads the queue, runs the worker on what it received and asserts. Because the endpoint comes from the environment, nothing in the application code changes between test and production.

    Add one test that sends the same event twice and asserts the action ran once. That is your idempotency regression guard.

// How to verify it works

  • pytest passes against ElasticMQ, including the duplicate-event and bad-signature cases.
  • Posting a signed sample returns 200 within a few hundred milliseconds even if the worker is slow.
  • Posting with a tampered body returns 401 and no message appears in the queue.
  • Making the worker raise on a test message results in it landing in the dead-letter queue after the third receive.
  • Sending an email containing a known pattern is forwarded to the mapped destination; unmatched text reaches the triage address.

// Design decisions and trade-offs

  • Acknowledge webhooks immediately and push the real work onto SQS
  • Verify HMAC signatures before parsing any payload
  • Make every handler idempotent using the provider event ID
  • Run the whole queue flow locally on ElasticMQ so tests need no AWS account
  • Route supplier emails by matching body content rules held in configuration, not code

// Pitfalls and lessons learned

  • Parsing the body before verifying the signature changes the bytes and breaks HMAC. Always verify on the raw body, and decode base64 first if API Gateway encoded it.
  • A visibility timeout shorter than the worker runtime causes the same message to be processed twice in parallel.
  • Returning an error from the receiver for downstream problems makes the provider retry, multiplying load. The receiver should fail only on bad signatures.
  • Without a dead-letter queue, poisoned messages loop until retention expires and quietly disappear.
  • Idempotency keyed on payload content instead of the provider event ID breaks when providers resend with new timestamps.
  • Email routing loops: a forwarded message that matches the proxy again will bounce forever unless you stamp and skip your own mail.

// Frequently asked questions

How do I handle a shopify webhook with aws lambda?

Put API Gateway in front of a receiver Lambda that verifies the HMAC header on the raw body, enqueues to SQS and returns 200, then process in a worker.

How do I avoid processing a webhook twice?

Record the provider event ID with a conditional write before acting; if the write fails, skip the event.

Can I test SQS code without AWS?

Yes. ElasticMQ implements the SQS API; point boto3 at its endpoint URL in tests.

What does a dead-letter queue do?

After a set number of failed receives, SQS moves the message to the DLQ so you can inspect and replay it instead of losing it.

Why not process the webhook inside the API request?

Slow or failing side effects cause the sender to time out and retry, repeating work that already succeeded.

// The outcome

Webhook bursts no longer time out the sender, failed jobs are retried and parked in a dead-letter queue instead of lost, and routing rules can be changed without redeploying. The same handler code runs against local ElasticMQ and real SQS.

// Where to take it next

  • Add a replay tool that redrives messages from the DLQ after a fix.
  • Alarm on DLQ depth and oldest message age.
  • Move to EventBridge when many consumers need the same event, similar to Automated IAM Compromise Detection and Credential Revocation.
  • Add structured logging with the event ID for end-to-end tracing.

// Keep reading