# Lab BUILD-SD-701 — PayRail Stripe-style idempotency

Source scenario: [PAKS — Stripe Payment Idempotency](https://paks.bayareala8s.com/docs/real-world-scenarios/stripe-payment-idempotency)

```text
Client → API Gateway → Charge Lambda
       → DynamoDB (idempotency_keys + orders + stripe mock)
       → SQS → Worker Lambda (webhook event_id dedupe)
       → EventBridge 1 min → Sweeper Lambda (stuck processing)
```

This is a **working AWS lab**. Deploy it, prove a timeout retry does not double-charge, then destroy it the same day.

Production at Stripe/merchant scale often uses **Aurora + ECS**. This lab uses **DynamoDB + Lambda** so a student account stays under **~$2** if you clean up today. The state machine is the same.

## What you build

| Path | What it is |
|------|------------|
| `lambda/charge.py` | `POST /v1/charges` — claim key, call gateway mock, cache response |
| `lambda/worker.py` | SQS consumer — dedupe `event_id` |
| `lambda/sweeper.py` | Heal rows left `processing` after a crash |
| `lambda/webhook.py` | `POST /webhooks/stripe` replay |
| `terraform/` | **Supported deploy path** |
| `scripts/local_server.py` | Same API on `:8080` with no AWS |
| `scripts/demo.sh` | Same key twice → same `order_id` |
| `tests/` | 8 pytest cases, no AWS |

## Prerequisites

- Python 3.11+
- For AWS: Terraform ≥ 1.5, an account that can create IAM, Lambda, API Gateway, DynamoDB, SQS, EventBridge, KMS
- `curl`
- Unique prefix such as `yourinitials-payrail`

## 1. Prove it locally (no AWS)

```bash
cd labs/payrail-idempotency
python3 -m pytest tests/ -v
python3 scripts/local_server.py
```

In another terminal:

```bash
./scripts/demo.sh
```

You should see `PASS: same order_id and payment_intent_id on retry` and HTTP **409** when the amount changes.

## 2. Deploy to AWS

```bash
cd terraform
cp terraform.tfvars.example terraform.tfvars
# edit name_prefix
terraform init
terraform apply
```

Note `charge_url`. Then:

```bash
../scripts/demo.sh
```

`demo.sh` uses Terraform outputs when `.terraform` exists.

## 3. Failure drill (ambiguous timeout)

```bash
curl -sS -X POST "$(terraform output -raw charge_url)" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-1" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"amount_cents":2500,"currency":"usd"}'
```

That leaves the key in `processing` (504). A retry with the same key returns **409 in flight**. Wait ~1 minute for the sweeper, or invoke the sweeper function. Then the same key returns the healed **201**.

## Validation

1. Same `Idempotency-Key` → same `order_id` and `payment_intent_id`
2. DynamoDB `orders` does not grow on retry
3. Same key, different `amount_cents` → 409
4. Missing key → 400
5. Store down (local: `store.down = True`) → 503 fail closed
6. SQS DLQ depth is 0 after a happy-path charge
7. CloudWatch log groups `/aws/lambda/{prefix}-charge` show the request

## Cleanup

```bash
cd terraform
terraform destroy
```

## Interview talking points

- After a timeout you are in **UNKNOWN** — do not assume failure and do not mint a new key
- Unique claim on `(tenant, key)`; replay returns the cached body
- Request hash rejects same key + different body
- Fail **closed** if the idempotency store is down
- Webhooks are at-least-once; dedupe `event_id`
- Sweeper + reconciliation are the backstop, not hope
- PayRail numbers in this sprint: **93/s** average, **1,200/s** Black Friday, p99 **< 400 ms**, 2% retries → **24 duplicate attempts/s** without the key
