Integrating with the WhatsApp Business Platform or a cloud telephony provider looks easy in a demo. You send a message with one API call, you receive a webhook when a customer replies or a call ends, and everything works. Then it goes to production, and you discover duplicate messages, missed call records, webhooks arriving out of order and a provider outage at the worst possible time.
None of these problems are exotic. They are the normal behavior of distributed systems talking over the internet. The fix is not clever code but a handful of well-known patterns applied consistently.
Treat inbound webhooks as untrusted and repeatable
Messaging and telephony providers deliver events by calling an HTTP endpoint you expose. Two facts shape how that endpoint should work. Anyone on the internet can call it, and the provider will retry if it does not get a quick success response, which means you will receive the same event more than once.
Verify signatures before doing anything else
Most providers sign each webhook with a shared secret, typically an HMAC over the raw request body sent in a header. Verify it against the exact bytes you received, before any JSON parsing, and use a constant-time comparison. Reject anything that fails with a 401 and log it. If the provider also sends a timestamp, reject events that are too old to limit replay attacks.
Acknowledge fast, process later
Do not call your CRM, send a reply, or run business logic inside the webhook handler. Verify, store the raw event, and return a 2xx. Processing happens asynchronously from that stored record. This keeps the endpoint fast enough to avoid provider timeouts, and means a bug in your processing logic does not cause the provider to retry and pile up duplicates.
Deduplicate with an idempotency key
Every event from a well-designed provider carries a unique identifier: a message ID, a call ID, an event ID. Store it with a unique constraint. If the insert conflicts, you have already seen this event, so return success and do nothing more.
@Slf4j
@RestController
@RequestMapping("/webhooks/messaging")
@RequiredArgsConstructor
public class MessagingWebhookController {
private final WebhookSignatureVerifier verifier;
private final InboundEventRepository events;
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> receive(@RequestHeader("X-Signature") String signature,
@RequestBody byte[] rawBody) {
if (!verifier.isValid(rawBody, signature)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
String eventId = EventIds.extract(rawBody);
// INSERT ... ON CONFLICT (provider, event_id) DO NOTHING
boolean isNew = events.insertIfAbsent("messaging", eventId, rawBody);
if (isNew) {
log.info("Stored inbound event {}", eventId);
}
// Processing happens in a separate worker that polls unprocessed events
return ResponseEntity.ok().build();
}
}
@Component
public class WebhookSignatureVerifier {
private final byte[] secret;
public WebhookSignatureVerifier(@Value("${messaging.webhook-secret}") String secret) {
this.secret = secret.getBytes(StandardCharsets.UTF_8);
}
public boolean isValid(byte[] body, String signatureHex) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
byte[] expected = mac.doFinal(body);
byte[] provided = HexFormat.of().parseHex(signatureHex);
return MessageDigest.isEqual(expected, provided);
} catch (IllegalArgumentException | GeneralSecurityException e) {
return false;
}
}
}The worker that processes stored events should also be idempotent. If it crashes after updating the CRM but before marking the event done, it will run again, so each side effect should either be safe to repeat or check whether it has already happened.
Outbound calls: the outbox pattern and retries
Sending a WhatsApp message or starting an outbound call is usually triggered by something in your own system, such as a booking being confirmed. The naive version saves the booking and then calls the provider API. If the API call fails, or your process crashes between the two steps, the customer never hears from you and nobody notices.
The outbox pattern fixes this. In the same database transaction that confirms the booking, insert a row into an outbox table describing the message to send. A separate worker reads pending outbox rows, calls the provider, and marks them sent. Because the business change and the intent to notify are committed together, you cannot have one without the other.
Retry with backoff, but only what is retryable
- Retry on timeouts, connection errors, 429 rate-limit responses and 5xx errors.
- Do not retry on 4xx validation errors like an invalid phone number or an unapproved template. Retrying will not fix them.
- Use exponential backoff with jitter, and respect any Retry-After header the provider sends.
- Pass an idempotency key to the provider when its API supports one, so a retry after an ambiguous timeout does not send the message twice.
- Cap the number of attempts. Retrying forever just hides the problem.
Dead-letter handling
Some events and messages will fail no matter how many times you retry: a payload your code does not understand, a customer record that was deleted, a template that was rejected. After the retry limit, move them to a dead-letter state with the error, the attempt count and the original payload.
A dead-letter queue is only useful if someone looks at it. Give support staff a simple screen to see failed items, understand why, and either replay them after a fix or discard them with a reason. Alert when the count grows unusually quickly, because that usually means something upstream changed.
Observability you will actually use
Integration problems are hard to debug after the fact unless you planned for it. The minimum we put in place:
- A correlation ID that follows an event from webhook receipt through processing and into any outbound calls, included in every log line.
- Metrics for events received, processed, retried and dead-lettered, broken down by provider and event type.
- Latency and error-rate metrics for each outbound provider API, so you can tell your bug from their outage.
- An alert when no webhooks have arrived for longer than normal. Silence is often the first sign that a subscription expired or a certificate changed.
- A timeline view per conversation or call, built from stored events, so support can answer what happened without reading logs.
Design for the provider changing
Finally, keep provider-specific code at the edges. Map incoming payloads into your own internal event types as early as possible, and send outbound messages through an interface that hides which provider is behind it. Providers change APIs, pricing and terms. When that happens, you want to rewrite one adapter, not every workflow that sends a message.
- telephony
- webhooks
- integrations
- reliability