What was already there
A colleague had built the API-key module: prefixed keys with the secret stored only as a hash, per-key scopes, rotation with a grace window, and an audit row for every call. It authenticated correctly, and I did not rewrite it.
What I added over the following months, in the order the gaps surfaced, was a generic template send endpoint (the only reason an outsider wants this API at all), a per-key rate limiter, idempotency, failures that name the responsible party, and list paging in the shape callers actually send.
Those look like five unrelated tickets. They are the same lesson five times: code that is correct for a caller who can read it is not correct for a caller who cannot.
Three parties can fail one send
Every send that WhatsApp rejected came back to the caller as HTTP 500, Request failed with status code 400.
The cause was one missing catch. The send path awaited the upstream call without one, so the raw HTTP client error reached the global exception filter, which maps an unknown throwable to 500 and prints only its message. The upstream had actually answered with a perfectly clear 400 and an error code meaning "this sender's display name was never approved". That answer existed, in full, in a container log nobody outside the company can read.
A partner seeing 500 cannot tell our outage from their own bug. Neither could we. And one status cannot fix it, because three different parties can fail a send and each needs a different answer.
| What failed | Owner | Answer |
|---|---|---|
| Sender account blocked or unapproved | the account | 409 META_ACCOUNT_BLOCKED |
| Malformed payload, unreachable recipient | the caller | 400 INVALID_SEND_REQUEST |
| Upstream throttling us | upstream | 429 META_RATE_LIMITED |
| Upstream 5xx, or no answer at all | upstream | 502 or 504 |
| Anything we do not recognise | us | rethrown, stays a 500 |
Two rows of that table were decisions rather than mappings.
An unrecognised upstream code degrades to "they rejected this" with their own status, not to a 400. Blaming the caller is the tempting default, because a 4xx reads like a definite answer and a partner integrating against you is the most likely source of a bad request. But accusing a partner of a bug that might be ours is the more expensive of the two mistakes, and it is the one they cannot check.
Our own faults get no status at all. The classifier returns nothing to answer with and the original error is rethrown:
// No response object means the request never got an answer, so there
// is nothing to attribute to the caller. Checked before anything that
// reads `error.response`.
if (httpStatus === undefined) {
if (transportCode && NETWORK_TIMEOUT_CODES.has(transportCode)) {
return meta(504, 'META_TIMEOUT')
}
if (transportCode && NETWORK_UNREACHABLE_CODES.has(transportCode)) {
return meta(502, 'META_UNREACHABLE')
}
// Not an HTTP failure and not a known transport failure: a TypeError,
// a DB error, a bug. Ours. No status - the caller must rethrow the
// original so the stack and Sentry grouping survive.
return {
source: 'internal', metaCode, reason, status: null, errorLabel: null
}
}
Wrapping our own bug in a tidy 500 would have cost the stack trace and the error grouping, which is the only thing that makes it fixable. The order matters too: transport failures are checked first, because there is no response to read, and reading a status off a refused connection is how a network fault gets blamed on the caller.
The owner travels in the response body as error_source, next to the upstream's own error code. A partner can branch on a field. Error strings are not an interface.
A retry that cannot send twice
Mobile integrations retry. A send that times out on the caller's side may well have gone out on ours, so a retry without protection is a second message and a second charge.
The interesting choice is not that there is an idempotency key, it is where the decision lives. Checking for an existing record and skipping if it is there loses the race: two requests with the same id both look, both find nothing, and both send. So the claim row is written before the work runs, and Postgres decides who owns it:
// Insert-first: we claim the key row BEFORE running `fn`, so two
// concurrent requests with the same id can't both send - the second
// loses the unique-index race and replays or conflicts.
await db.insert(externalIdempotencyKeys).values({
company_id: companyId,
endpoint,
request_id: requestId,
status: 'pending'
})
return true // we own the claim
A unique violation means somebody else owns it. If their row says completed, the stored response body is replayed without re-running anything. If it still says pending, the caller gets a 409 saying the request is in flight, which is a true statement and a safe one.
Three details only matter once it is live:
- A claim whose work threw is deleted, so a genuine retry of the same id can run. A key that permanently poisons an id after one transient failure is worse than no key at all.
- A pending claim older than two minutes is treated as abandoned and taken over, because the process that wrote it can die between the insert and the result, and that id would otherwise be unusable forever.
- No id supplied means no guarantee and the work simply runs. That kept the field optional, so nothing that already called the API had to change.
The piece I liked finding later: when sends are refused because a customer's plan has lapsed, the refusal happens before any lookup and releases the claim, so the same client_request_id works once the plan is renewed. Two features compose correctly only if you remember the first one exists while writing the second.
Refusing a send that was going to fail
A different kind of problem, and the one I would not have anticipated. WhatsApp rates a sender number partly on how its messages land, and one-time codes sent to numbers that are not on WhatsApp at all drag that rating down for every other message from the same number. The caller cannot know which numbers those are. Neither can we, until the delivery report comes back.
So an OTP send now checks the number's own history first, ahead of the contact, the sender account and the credit balance: two or more undeliverable sends inside the window with nothing ever delivered or read, and the send is refused with a 422 and a message telling the caller to fall back to SMS. A refusal contacts nothing upstream, charges nothing, and creates no contact record.
What makes it safe to leave on:
- The refusal writes a log row marked as a refusal, and the rule counts only real send attempts. A suppression rule that counts its own output ratchets toward refusing everything.
- History written as
91...and as+91...counts as one number, because the same phone arrives both ways. - A blank or unparseable number falls back to allowing the send. One malformed row must not be able to refuse every send.
page is not an exotic request
The external list endpoints reused the internal filter type, which takes skip and a limit from a fixed set of 10, 20, 50, 100 and 200. The global validation pipe runs with forbidNonWhitelisted, which turns any unrecognised query parameter into a 400.
So a caller asking for ?page=1&limit=5, which is what very nearly every API on the internet accepts, got this:
property page should not exist,
limit must be one of the following values: 10, 20, 50, 100, 200
Nothing was broken. Every test passed. The endpoint did exactly what it was designed to do. It was simply unusable by anyone who had not read our internal code, and the people calling it were generating their client from our published documentation.
The fix is deliberately small. External-only filter types reuse the internal ones and add a pagination type where page starts at 1 and limit is any whole number from 1 to 200, plus one function that turns page into the skip the services already read:
/** Turns `page` into the `skip` the services read, and drops `page`. */
export function resolveExternalPage<T extends {
skip?: number; limit?: number; page?: number
}>(filters: T): Omit<T, 'page'> {
const { page, ...rest } = filters
if (page === undefined) return rest
return { ...rest, skip: (page - 1) * (rest.limit ?? DEFAULT_LIMIT) }
}
No list service changed, and the internal endpoints kept their stricter type. A public API's shape should not be a side effect of an internal convention, but relaxing it should not force the internals to relax with it.
The accompanying test drives the four real controllers through the framework's routing with the services mocked, and asserts that page=3&limit=5 arrives at the service as skip=10, limit=5 with no page at all. 7 of its 11 tests fail against the old controllers, which is the part that makes it a test rather than a description.
Proving a change touched nothing else
An internal endpoint that regresses is a bug report. A public one is a partner's outage, found by their customers, and they will not have read our changelog. So "the new tests pass" was not the claim I wanted to ship on.
I built a harness that runs the same 74 steps against two builds of the server, the current production code and the branch, and diffs every response. Both are real compiled servers running against a throwaway Postgres and Redis. Every upstream is redirected: the messaging provider to a stub that logs each call, so a send is observable without a message existing, and everything else to a closed port, so nothing can quietly reach the internet.
The steps cover authentication and scope rejection, every list and CRUD route, template create, update, sync and send, OTP send and logs, campaign create, preview, analytics and delete, and the rate limiter: 61 rapid calls, expecting 60 answers and then a 429.
| Run against | Steps meeting expectation | Unmatched upstream calls |
|---|---|---|
| Production code | 74 / 74 | 0 |
| The branch | 74 / 74 | 0 |
| 59 of 74 responses byte-identical after masking ids and timestamps | ||
The 15 that differed were the 15 the change was for: 13 requests that used to be rejected now succeed, and 2 are still 400 with a clearer message. Reading that list of 15 was the real review. Had a sixteenth been there, that would have been the bug.
It also found three things that were not the paging bug:
- The published request collection sent
bodywhere the API wantsbody_text, and omitted a required field, so the documented way to create a template returned 400 on both builds. The documentation had never been executed. - Two documented log URLs sent an empty
status=, which fails an enum check and returns 400. - The campaigns list demanded a
company_idthe code never reads, since the list is already scoped to the key's company.
Documentation nobody runs is a second implementation with no tests. Replaying the published collection as written, against the real server, cost an afternoon and found three bugs that no amount of reading would have.
A read-only version of the same assertions runs against a deployed server and creates nothing. It passed 37 of 37 on staging against real data and 37 of 37 on production after the release, each time with a database backup taken first and against a temporary key that was revoked immediately afterwards.
What is not done
- Delivery status is polled rather than pushed. That is fine at the volumes involved and will not stay fine, and outbound webhooks are the natural next piece.
- The harness is a local script, not CI: it needs Docker, two built checkouts and about eight minutes, so it runs when an external change is released rather than on every commit. Scheduling it is the obvious next step, and would have surfaced the paging problem months earlier.
- A rate limiter belongs in one place as a global default with explicit exemptions, rather than being attached route by route. Wiring it per route makes the policy a property of how the code is assembled instead of a property of the API.
What I took from it
- An error a caller cannot act on is not an error message. Give them the owner of the failure, in a field, not in prose.
- Make the database the arbiter of "has this already happened". Insert first: a unique index does not lose races, and a check beforehand always can.
- The shape of a public endpoint is part of its contract. Inheriting it from an internal convention means publishing a convention you never chose, to people who cannot see it.
- For anything a stranger calls, "the new tests pass" is the weaker claim. "Every other response is identical" is the one worth making, and it needs the old build still running to be worth anything.