Yash Gupta

Moving a live message channel without sending anything twice

Every invoice our Django ERP creates is sent to the business owner as a PDF on WhatsApp, through an outside provider we pay per message. We have our own WhatsApp platform, so that traffic should come home. The interesting part is not the new send. It is that a fallback to the old provider is only safe when "it failed" means "nothing was sent", and sometimes you cannot know that.

Role
Designed and built it, solo
Stack
Django, Python, MySQL, WhatsApp Business API
Status
Built and in review, not merged
Tests
33, four against a real database

The shape of the change

One method on one helper sends every document PDF a company creates: invoices, quotations, credit notes, delivery challans. It sends two kinds of copy, one to the business owner's own number and one to their customer. Only the owner copy moves, and only for some companies at first.

So the change at the call site is two lines: ask whether this company's copies go through our platform, and if our platform took it, return instead of calling the old provider.

else:
    # the owner copy: try our own platform first
    if self.__send_owner_copy_via_platform(file_url):
        return
    company_number = self.company.effective_whatsapp_number

Everything difficult is behind that boolean.

A fallback is a duplicate waiting to happen

"Try the new provider, fall back to the old one on failure" is the obvious design, and it is wrong as stated. A business owner who receives their invoice twice is a support ticket and a dent in trust. We are also paying twice, which was the point of the exercise.

The fallback is only correct when a failure proves nothing went out. Some do. Some do not, and they look identical from the caller's seat unless you go and decide what each one means.

What came backDid a message go out?What we do
200yesdone
401, 400, 402: refusedno, it never reached WhatsAppold provider
Connection refusedno, we never connectedold provider
502 or 503 from a proxyno, the platform is down or restartingold provider
504 gateway timeoutunknown, a send was under waynothing
Read timeoutunknown, the request arrivednothing
Connection dropped after sendingunknownnothing
Unparseable answerunknownnothing

The three outcomes in the code are named for what they assert, not for whether they went well: SENT, FALLBACK, and UNSURE, whose comment reads "no clear answer and it may well have gone out, so do not send it again".

Choosing which risk to take is the whole decision. On an uncertain outcome we accept that the owner might receive nothing, rather than that they might receive two copies of the same invoice. That is a judgement about this message, not a universal rule: a one-time passcode would deserve the opposite call, because a second code is an annoyance and a missing one is a locked-out user.

Reading my own error labels from the other side

Our platform's send endpoint answers a failed hop to WhatsApp with a label naming who is at fault. I had written those labels, in TypeScript, on the other side of this call. Calling them from Python was the first time I had to ask what they are worth to someone making a retry decision.

Two of them mean the hop was made and the answer did not come back, so a message may exist:

# Our platform's labels (error_source "meta") for a send whose hop to
# WhatsApp ended without a clear answer, so the message may have gone
# out. META_UNREACHABLE is not one of them: the platform could not
# connect at all, so nothing went out.
UNCERTAIN_SEND_ERRORS = frozenset(
    {"META_TIMEOUT", "META_UPSTREAM_ERROR"}
)

And one of them, sitting right next to those two in the same response shape and the same HTTP status family, means the opposite: nothing was attempted, so falling back is not just safe, it is required.

That distinction is only legible because the labels distinguish a transport failure from an upstream rejection. Had the platform answered every failed send with one generic error, as it did before that work, there would have been no safe way to write this caller at all. An error taxonomy is not documentation. It is the thing that decides whether your caller can retry.

It also exposed a gap I would not have seen from the server side. The platform returns 500 for its own internal faults, and I had to go and check that the code path which records a sent message cannot throw, because if it could, a 500 might mean "sent, then failed to write it down" and the whole fallback would be unsafe. It cannot, so a 500 is treated as nothing-sent. That is a fact about today's code, which is a weaker guarantee than I would like.

Shipping it switched off

The feature is dormant when it merges. It does nothing until two environment values are set, and then still nothing until a row in the database says so.

  • A percentage, read at send time. Ramping from 5 to 20 is an edit in the admin, not a deploy. Stopping is setting it to zero, which takes effect on the next document.
  • An allowlist of company ids that are always in. This exists because the platform allows one active API key per company, so minting a test key would have revoked the live one used for passcodes. Instead we test against a real company at zero percent.
  • A sticky bucket. A company's bucket is a SHA-1 of its id taken modulo 100, so it never changes. Raising the percentage only ever adds companies; nobody who has been receiving messages from the new number gets moved back. A random draw per send would have scattered one company's invoices across two sender numbers.

A test pins that property rather than describing it: the set of companies in the share at 5 percent must be a strict subset of the set at 10 percent, checked over two thousand generated ids. Another sends ten thousand through the bucket function and requires between 400 and 600 to land in the first five percent, which is a loose enough bound to not be flaky and tight enough to catch a hash that clumps.

Nothing reads the database at all until the environment is configured, and there is a test for that too, asserting the query was never issued. A dormant feature that still runs a query per document is not dormant.

Two things that only production teaches

The shared HTTP helper would have logged every owner's phone number. Every outbound call in the codebase goes through one base class, which logs the full request and response body to cloud logging. It redacts carefully, and the comment above the redaction explains why: card numbers and gateway credentials. Phone numbers are not in that list, because nothing that used the helper before had one in the body. This request does. The subclass overrides the log to record the URL, the status, the response time and the last four digits only, and masks any run of ten or more digits in an error message. A safeguard built for one class of sensitive data silently does not cover the next one.

The override also cannot throw. Logging runs on a background thread wrapped in a catch-all, because an exception while writing a log line must never turn a message that was sent into a message that gets sent again by the fallback. There is a test named for exactly that.

Production web pods print warnings and above. An earlier draft logged every outcome at info level, which would have been correct and invisible. A fallback is not a normal event: it means an expired key, no credits, or a wrong template id, and it is silently costing money at the old provider. Every outcome other than success now logs at warning.

How it was checked

33 tests. Most are pure, and the valuable ones are the ten that each pin one row of that table: a read timeout does not send a second copy, a gateway timeout in front of the platform does not send a second copy, a connection dropped after the request went out does not send a second copy, and the platform being unreachable does fall back. The test names are the specification.

Four run against a real database rather than a mock, because the share lookup reads the newest configuration row and .last() against a mocked queryset tests the mock. I checked that one by mutation: changing .last() to .first() has to fail the newest-row test, and it does. A test that passes against both versions of the code was not testing the thing.

The rest of the suite pins what must not change: the customer copy, and the three other document types that share the same method, still go to the old provider untouched.

What is not done

  • It is not merged. The branch is in review, and it is deliberately the kind of change that is safe to sit behind a switch while that happens.
  • Only the owner copy moves. Customer copies are a larger decision, because they go to people who never agreed to hear from us on a different number.
  • There is no reconciliation. An uncertain outcome is logged and left, and nothing afterwards checks whether that message actually arrived. The platform does have delivery logs, so a job that closes the loop is the obvious next piece.
  • The uncertainty rule is mine, written from reading the sending code on both sides. It is not a guarantee either provider offers in writing, and it would need revisiting if either changed.

What I took from it

  • A fallback needs a proof, not a failure. Before writing one, enumerate the failures that prove nothing happened, and treat everything else as "it might have".
  • Decide which duplicate you can live with, per message type. There is no general answer, and answering it generally is how you get two invoices or no passcode.
  • Migrate live traffic with a dial you can turn without a deploy, and make the selection sticky so turning it up never moves anyone back.
  • Being the caller of your own API is the cheapest review it will ever get.