TalkAm is a voice-banking app I built on WhatsApp. A user sends a voice note, something like "send 5,000 to my brother", TalkAm transcribes it, reads the transfer back, and moves the money once the user clears a PIN or a face check.
Every one of those voice notes reaches TalkAm through a single endpoint: the WhatsApp Cloud API webhook. And that webhook has a property that's easy to miss on a first build: Meta retries any delivery it doesn't get a prompt 200 for.
In most apps a retried webhook is a nuisance. In a banking app it's a second instruction to move money. This article walks through how TalkAm's webhook is built so that a retry, a race or a crash can never turn one voice note into two transfers.
Why a slow webhook becomes a duplicate transfer
The tempting first version does the work inside the request. The voice note arrives, you download the audio, send it to speech-to-text, ask the language model what the user wants, and reply. It works on your laptop.
In production, speech-to-text can be slow. One slow transcription and the request outlives Meta's patience. Meta sees no 200, assumes the delivery failed, and sends the same message again. Now two requests are transcribing the same "send 5,000 to my brother".
You might hope the bank's idempotency key saves you. It doesn't. That key is generated per transfer attempt, so a second run of the same voice note generates a fresh reference, and the bank sees two perfectly valid, different transfers. Two debits.
The fix has to live at the boundary where the duplicate first appears: the webhook itself.
The handler does three things: record, queue, return
TalkAm's webhook controller does exactly three things for each message in a delivery. It records the event, which is also where duplicates are caught. It queues the real work. And it returns.
public function receive(Request $request): JsonResponse { $events = $this->translator->translate($request->all()); $queued = 0; $duplicates = 0; foreach ($events as $event) { $record = $this->record($event); if ($record === null) { $duplicates++; continue; } ProcessInboundChannelEvent::dispatch($record->id, $event); $queued++; } // Always 200, even for a payload we made nothing of. return response()->json([ 'received' => count($events), 'queued' => $queued, 'duplicates' => $duplicates, ]); } Transcription, intent extraction and the transfer state machine all run in the queued job. The request never waits on a speech service, so it can answer promptly, and the most common cause of retries is gone.
The translator in front of it turns Meta's payload into one normalised event per message. Meta can batch several messages into one delivery, so each one is recorded and queued on its own. A message with no id or no sender is dropped: without an id there's no deduplication key, without a sender there's nobody to act for, and guessing would be worse than dropping it.
The signature check runs before any of this, as route middleware: no valid HMAC-SHA256 signature from Meta, no record. That's a story of its own; here I'll stay with what happens after a request is proven genuine.
The unique index is the real guarantee
Moving the work to a queue makes retries rarer. It doesn't make them impossible: networks drop responses, and Meta will still redeliver now and then. So every inbound message is written to a channel_events table first, keyed on the provider's own message id.
Schema::create('channel_events', function (Blueprint $table) { $table->id(); $table->string('channel', 20); $table->string('event_type', 40); $table->string('external_id'); // the provider's own message id $table->string('sender_ref', 40)->index(); $table->jsonb('payload')->nullable(); $table->timestamp('processed_at')->nullable(); $table->string('processing_outcome', 40)->nullable(); $table->timestamps(); $table->unique(['channel', 'external_id']); }); The table does two jobs. It's the start of the audit trail, so a transfer can be traced back to the exact message that asked for it. And the unique index on (channel, external_id) is what makes a redelivery a no-op.
Here's the method that writes to it:
private function record(InboundEvent $event): ?ChannelEvent { $existing = ChannelEvent::where('channel', $event->channel) ->where('external_id', $event->externalId) ->first(); if ($existing !== null) { return null; } try { return ChannelEvent::create([/* channel, type, external_id, sender, payload */]); } catch (UniqueConstraintViolationException) { return null; } } The lookup handles the ordinary case: a redelivery that arrives after the first copy is safely stored. The try/catch handles the case the lookup can't. Two copies of the same message arrive at once, two requests both look, both see nothing, and both try to insert. Only one insert survives the unique index. The other gets a constraint violation, which the code treats as exactly what it is: a duplicate.
A check-then-insert without the index looks correct and passes every test you'd think to write. It fails under concurrency, which is precisely when retries show up. The database is the only part of the system that sees both requests at once, so it's the part that gets the final say.
Always 200, even for nothing
The controller returns 200 for every request that passes the signature check, including payloads it made nothing of. That covers delivery-status updates, which carry no messages, and message types TalkAm doesn't handle, which are recorded as unsupported and never treated as an instruction.
It feels wrong to answer "OK" to something you didn't use. But a non-2xx tells Meta to retry, and retrying won't make an unsupported message type supported. It will just deliver the same thing again and again. The response body still says what happened (received, queued, duplicates), so the information isn't lost; it's just not expressed as a failure Meta would act on.
The job checks again before it acts
The queued job is the second line of defence. Before it does anything, it reloads the record and looks at processed_at:
$record = ChannelEvent::find($this->channelEventId); if ($record === null || $record->processed_at !== null) { // Already handled, or the record is gone. Either way, doing it // again is the one thing that must not happen. return; } try { $outcome = match (true) { /* audio, text, PIN entry, face capture, ... */ }; } catch (Throwable $exception) { $record->markProcessed('failed', $startedAt); throw $exception; } $record->markProcessed($outcome, $startedAt); Each path through the job ends by stamping the record with a time and an outcome: a transfer started, an onboarding step advanced, an ignored type. That includes failure. If a turn throws, the record is marked failed before the exception goes back to the queue, so when the queue retries the job, it finds processed_at already set and stops.
That's a deliberate trade-off. A turn that died halfway is not replayed automatically, so the user may have to send their voice note again. The alternative is a queue retry re-running a turn that may already have created a transaction. For instructions that move money, asking someone to repeat themselves is the cheaper failure.
Proving it with tests
The guarantees are pinned down in feature tests, so a refactor can't quietly undo them. One sends the same signed message twice and asserts that it was stored and queued once:
it('processes a redelivered message exactly once', function () { Bus::fake(); signedPost(whatsAppBody('wamid.retried'))->assertOk()->assertJsonPath('queued', 1); signedPost(whatsAppBody('wamid.retried'))->assertOk()->assertJsonPath('duplicates', 1); expect(ChannelEvent::count())->toBe(1); Bus::assertDispatchedTimes(ProcessInboundChannelEvent::class, 1); }); Others check the rest of the contract: the request makes no outbound HTTP calls at all, the event is recorded before it's queued, every message in a batched delivery is queued, a genuinely different message is still accepted, and an empty payload still gets a 200.
The "no outbound calls" test is the one I'd copy first. It fakes the HTTP client and asserts nothing was sent during the request. If someone later adds a "quick" API call to the webhook, that test fails before Meta's retries find it in production.
What I'd tell anyone building a payment webhook
- Deduplicate at the boundary, on the provider's message id. Your own downstream keys are generated too late to recognise a repeat.
- Let a unique index make the final call. Application-level checks race; the database doesn't.
- Record, queue, return. Nothing slow belongs in the request, because slow is what triggers the retry.
- Return 200 for anything you've recorded or can't use. A failure status is an instruction to the sender to try again.
- Make the worker check again, and mark failures as processed if a replay could be worse than a repeat.
None of this is specific to WhatsApp. Payment providers, SMS gateways and IVR platforms all retry, and all of them will eventually deliver the same thing twice.
How does your system make sure a retried webhook can't do the same work twice?