QUALIA BITS ## Journal

[journal]

AI Call Webhooks: Handle Duplicates Without Reopening Finished Calls

AI Call Webhooks: Handle Duplicates Without Reopening Finished Calls
call webhooksevent processingidempotencyCRM integrationvoice AIreliability

A call ends, your dashboard marks it complete, and a delayed ringing callback arrives. If the last request wins, the dashboard sends the call backwards. A retry can also repeat the CRM update or follow-up task. These are event-processing problems, not voice-model problems.

Start with one documented callback stream

This guide uses Twilio Programmable Voice call-progress callbacks as a concrete example. It is an implementation pattern, not a claim about features already deployed in a QualiaBits product. Other providers and event streams need their own identifiers, ordering rules and retry checks.

Twilio documents a SequenceNumber for these callbacks, starting at zero. Events are fired in sequence, but their separate HTTP requests are not guaranteed to arrive in that order. CallSid identifies the call; ParentCallSid identifies its parent when present. Keep separate call legs separate. [SRC001]

Do not confuse the subscribed event with the outcome. The completed callback event can describe a call that ended busy, failed, canceled or unanswered. Read CallStatus rather than translating every completed event into a successful conversation. Even CallStatus=completed is not proof that the caller's business problem was resolved. [SRC001]

Authenticate, record, then acknowledge

Use the provider SDK's signature validator before trusting the payload, and configure it for the actual external request URL and request format. Twilio recommends its SDK helpers and checks for account and resource ownership. A signature does not replace application validation of fields or tenant routing. [SRC002]

Our recommended receiving path is: validate the signature and payload; commit a durable inbox record; return HTTP 200; let a worker do the slow work. Twilio recommends prompt responses rather than waiting for downstream processing. [SRC002] The durable inbox before acknowledgement is our reliability addition: returning success and then crashing before enqueueing would leave no work to recover.

If the durable write fails, do not return a false success. Handle the failure within the provider's timeout budget and your configured retry policy. Keep an alert and a reconciliation route for missed events. A non-2xx response is not a promise of a retry: Twilio's connection overrides distinguish connection, read-timeout and HTTP-status retry policies. [SRC003]

Separate event identity from current state

For this specific call-progress stream, a proposed inbox key is provider + account + callback source + CallSid + SequenceNumber. Validate all parts before using the key. Do not use CallSid alone: it would collapse ringing, answered and ending updates into one record. Do not carry this key design into recording callbacks or another provider without checking their contract. [SRC001] [SRC004]

Put a unique constraint on that composite key. A separate read-then-insert check is not a concurrency boundary. PostgreSQL documents ON CONFLICT as a way to handle a uniqueness conflict during the insert. [SRC005] Keep the inbox insert and the relevant database changes inside the intended transaction.

Save an appropriate payload fingerprint too. The same key with different content should raise a conflict for investigation rather than silently replacing evidence. Apply access controls and a retention policy to stored callback data; avoid dumping entire payloads or authentication material into ordinary application logs.

Then maintain a small latest-state projection. For the same call leg and callback stream, accept a status only when its sequence is newer than the stored sequence. An older event can remain in the inbox without changing the dashboard. Ordering the projection is not the same as discarding the historical event.

A small, testable projection function

This JavaScript function assumes that identity, signature, tenant ownership and stream selection were checked earlier. It only selects the latest status for one call-progress stream. SequenceNumber is supplied as a form-field string. Unknown values fail closed for investigation; production systems need an explicit quarantine and recovery path.

export function project(current, event) {
  const raw = event.SequenceNumber;
  if (typeof raw !== 'string' || !/^\d+$/.test(raw)) {
    throw new Error('Invalid sequence');
  }
  const seq = Number(raw);
  if (!Number.isSafeInteger(seq)) throw new Error('Invalid sequence');
  const allowed = new Set([
    'queued', 'initiated', 'ringing', 'in-progress',
    'completed', 'busy', 'failed', 'no-answer', 'canceled'
  ]);
  if (!allowed.has(event.CallStatus)) throw new Error('Unknown status');
  if (current && seq <= current.sequence) return current;
  return { sequence: seq, status: event.CallStatus };
}

An example delivery order of sequence 3/completed, then 1/ringing, then 3/completed leaves the projection at completed. It does not reopen the call or apply the same sequence twice.

The sample was tested locally against stale and duplicate events, forward progress, invalid sequence values, unknown statuses, five ending outcomes, and all 24 delivery permutations of four progress events. These are pure-function tests, not proof of database concurrency safety or a production integration.

In a real worker, protect the comparison and update with a database transaction and row lock, or a conditional atomic update. Calling this function after an unlocked database read is insufficient when two workers run together. Older callbacks can still supply useful historical metadata, so retain and process that separately from the latest-status projection.

A database transaction does not make the CRM atomic

Suppose the worker updates the call row and then creates a CRM task. A crash between those operations can lose the task. Reversing the order can create duplicates on retry. Our recommendation is to write the state change and an outbox job in the same database transaction, then let a separate worker deliver that job. AWS describes this transactional outbox pattern and warns that consumers still need to handle duplicate messages. [SRC006]

Give each business action its own stable idempotency key, such as account + call leg + action type + action version, where those fields match the intended business rule. Event deduplication and business-action deduplication solve different problems. A call can generate many legitimate events but require only one end-of-call summary task.

Use the downstream service's idempotency facility when available. An outbox alone cannot guarantee exactly one external side effect: the remote API may accept a request just before your worker crashes. If the destination offers no deduplication mechanism, document the ambiguity and add reconciliation instead of promising exactly-once delivery.

Test the failures before adding traffic

Replay duplicates concurrently, deliver the ending callback before ringing, and interrupt the worker before and after the database commit. Simulate a remote timeout after the CRM has accepted the request. Check separate parent and child legs, malformed sequence values and a genuine failed-call outcome.

Track inbox-write failures, duplicate keys, conflicting payloads, stale projection attempts, oldest pending outbox job and unresolved delivery ambiguity. Choose alert thresholds for the deployment rather than copying an unsupported universal number.

The useful launch question is not whether the webhook endpoint returned 200 in a demo. It is whether delayed, repeated and interrupted delivery leaves a recoverable record and the right business outcome.

FAQ

Can I just ignore every callback after completed?

Not as a universal rule. Keep the callback history, scope ordering to its documented stream, and process recording or other event types separately. A latest-status projection should not erase later-arriving evidence.

Does an outbox guarantee exactly one CRM update?

No. It makes the local state change and delivery intent atomic in your database. The destination still needs idempotency or a reconciliation process for ambiguous retries.

Sources

  1. TwiML Voice: Number, call-progress events and callback parameters - Twilio
  2. Webhook security, validation and prompt responses - Twilio
  3. Webhook connection overrides and retry policy - Twilio
  4. Voice webhooks and status callback scope - Twilio
  5. PostgreSQL: INSERT, uniqueness and ON CONFLICT - PostgreSQL Global Development Group
  6. Transactional outbox pattern - AWS Prescriptive Guidance

Evidence map

  • Twilio call-progress callbacks carry a SequenceNumber starting at zero, are fired in sequence but not guaranteed to arrive in order, and the completed event fires regardless of whether the call ended busy, failed, canceled or unanswered.
    Evidence: SRC001
  • A non-2xx webhook response is not by itself a promise of a retry; connection, read-timeout and HTTP-status retry policies are configured separately.
    Evidence: SRC003
  • PostgreSQL ON CONFLICT provides insert-time uniqueness handling that a separate read-then-insert check cannot guarantee under concurrency.
    Evidence: SRC005
  • The transactional outbox pattern writes the state change and the delivery intent in one database transaction, and consumers still need duplicate handling.
    Evidence: SRC006
See how CallPulse structures every call
Chat with us