The DynamoDB mock that cost us a day of orders
A mocked DynamoDB client let a bad write through and we lost a day of orders. This is the two-layer setup we use now to test Lambda, SQS and API Gateway in CI.
A couple of summers ago we shipped a change to our order service on a Friday afternoon. Every test was green. By Saturday morning, support had a queue of customers asking why their orders said "processing" and never moved.
The bug was boring. A Lambda wrote order records to DynamoDB, and someone had renamed the table's sort key from
orderId to order_id in the infrastructure code. The handler still wrote orderId . Our unit tests used a mocked DynamoDB client that accepted whatever item shape we handed it. The real table rejected the write with a ValidationException, the Lambda caught it in a try/except that only logged a warning, and the order vanished. The mock had no idea the table even had a key schema.That weekend changed how my team tests anything that talks to AWS.
Why mocks lie about AWS services
A mocked boto3 client tests your code against your own assumptions. If your assumption about the table is wrong, the mock is wrong in exactly the same way, and the test passes. That's the whole problem in one sentence.
DynamoDB is a good example because it enforces things a mock won't: key schemas, conditional expressions, reserved words, item size limits. SQS has visibility timeouts and message attributes. API Gateway has request validation and mapping templates that reshape the payload before your Lambda ever sees it. None of that lives inside
MagicMock() .So I don't trust a passing suite for a service that touches three AWS resources unless some of those tests hit something that behaves like the real thing. On our team, that's what integration testing means in practice: checking that the pieces agree with each other, instead of each piece agreeing with itself.
What we test against now
We run two layers.
For fast feedback, LocalStack runs in Docker during CI. It has gaps (more on that later), but it does enforce DynamoDB key schemas and lets us create tables and queues from the same definitions we deploy. Moto is fine too if you're all Python and want everything in-process. Pick whichever one your team will actually keep maintaining.
For the things LocalStack fakes badly, we deploy a short-lived stack per pull request into a sandbox account and run a smaller suite against real endpoints. Slower. Costs a bit. It also caught an IAM policy missing
dynamodb:PutItem on a brand new table, which nothing local would have flagged.Here's roughly what one of our DynamoDB tests looks like. The table gets created from the same schema file our CDK stack reads, and that's the part that matters.
import json, os, boto3, pytestfrom orders.handler import create_order
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566")
@pytest.fixturedef table(): ddb = boto3.resource("dynamodb", endpoint_url=ENDPOINT, region_name="us-east-1") with open("infra/tables/orders.json") as f: t = ddb.create_table(**json.load(f)) t.wait_until_exists() yield t t.delete()
def test_order_is_actually_stored(table): event = {"body": json.dumps({"customerId": "c-42", "items": [{"sku": "A1", "qty": 2}]})} resp = create_order(event, None) assert resp["statusCode"] == 201
order_id = json.loads(resp["body"])["orderId"] item = table.get_item(Key={"customerId": "c-42", "orderId": order_id}).get("Item") assert item is not None, "handler returned 201 but nothing was written"That last assertion would have saved our weekend. A 201 tells you the handler thinks it worked. Reading the row back tells you it did.
Service-to-service calls through SQS
Async flows gave us the flakiest tests we've ever had. The order Lambda drops a message on SQS and a fulfillment worker picks it up. Our first version of the test sent the order, then polled the queue exactly once. Locally it passed every time. In CI it failed maybe one run in five, because the runner was slower and the message wasn't visible yet.
What worked for us was polling with a deadline instead of a fixed sleep, and asserting on the shape of the message body, not only that something arrived. We also set
WaitTimeSeconds on the receive call so it long-polls instead of hammering the endpoint. A time.sleep(5) will pass on Tuesday and fail on Thursday. I've stopped approving PRs that add them.One more habit I'd push for. Keep the contract between producer and consumer in one place. We store a JSON schema for the queue message, and both services validate against it in their own tests. When someone adds a required field on the producer side, the consumer's test breaks in the same pipeline run instead of in production at 2am.
Where it fits in CI/CD
Our pipeline ended up like this:
- unit tests with mocks, under a minute
- LocalStack tests in a Docker service container, around four minutes
- a per-PR sandbox stack with a smoke suite against real API Gateway and DynamoDB, about ten minutes, only when a PR touches handlers or infra
I used to want everything in that last bucket. It got slow, and people quietly started skipping it. Running it only when the relevant files changed fixed that.
Some of our services run on ECS rather than Lambda, and for those, record-and-replay tools are handy. Keploy, for example, can capture real API traffic from a running container and turn it into test cases. It doesn't work inside the Lambda runtime, though, so for our functions we stick with deployed-stack tests.
The part LocalStack gets wrong
I like LocalStack, but I don't fully trust it. It skips IAM evaluation by default, and support for newer service features tends to trail AWS by a while. We once had a test pass locally that relied on DynamoDB behavior the emulator handled a little differently from the real service. That's exactly why the sandbox layer exists. Use the emulator as a quick first filter and let the real account have the final say.
If you only change one thing after reading this, make it this: after any write to a data store, read it back in the test and check the fields. It's three lines of code, and it's the assertion I wish we'd had on that Friday.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article