<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Voice Pilot Engineering]]></title><description><![CDATA[Voice Pilot Engineering]]></description><link>https://voicepilotai.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b0cf8828fbca363290d1dd4/20f7fc97-fe99-47e0-b650-80bd0c990461.png</url><title>Voice Pilot Engineering</title><link>https://voicepilotai.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 19:36:35 GMT</lastBuildDate><atom:link href="https://voicepilotai.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Two webhooks, one millisecond, two duplicate contacts: fixing a race with SELECT … FOR UPDATE]]></title><description><![CDATA[Two webhooks for the same call arrived in the same millisecond and created duplicate contacts. How a row lock on the call fixed it, and how to test it.]]></description><link>https://voicepilotai.hashnode.dev/two-webhooks-one-millisecond-two-duplicate-contacts-fixing-a-race-with-select-for-update</link><guid isPermaLink="true">https://voicepilotai.hashnode.dev/two-webhooks-one-millisecond-two-duplicate-contacts-fixing-a-race-with-select-for-update</guid><category><![CDATA[Python]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[sqlalchemy]]></category><dc:creator><![CDATA[Équipe Voice Pilot]]></dc:creator><pubDate>Mon, 30 Nov 2026 04:22:52 GMT</pubDate><content:encoded><![CDATA[<p>Our telephony provider sends two webhooks at the end of every call: one when the call ends, one a few moments later when the post-call analysis is ready. Most of the time they arrive seconds apart. Sometimes they arrive in the <strong>same millisecond</strong>, handled by two different workers. For a few weeks, that produced duplicate contacts in our customers' address books. Here is what happened and the small fix that removed it.</p>
<h2>The bug</h2>
<p>Voice Pilot answers phone calls for small businesses. When a new caller phones in, we link the call to a contact: we look the caller up by phone number and, if nobody matches, we create a new contact. The handler looked roughly like this:</p>
<pre><code class="language-python">def link_inbound_caller(db: Session, call: Call) -&gt; None:
    if call.contact_id:                      # already linked by the other event?
        return
    contact = find_contact_by_phone(db, call.organization_id, call.caller_phone)
    if contact is None:
        contact = Contact(organization_id=call.organization_id, phone=call.caller_phone)
        db.add(contact)
        db.flush()
    call.contact_id = contact.id
</code></pre>
<p>Both webhooks call this function. Read it with two workers running it at the same time:</p>
<ol>
<li>Worker A loads the call: <code>contact_id</code> is empty.</li>
<li>Worker B loads the same call: <code>contact_id</code> is still empty, because A has not committed yet.</li>
<li>Both look the caller up: nobody yet.</li>
<li>Both create a contact. Both commit.</li>
</ol>
<p>The <code>if call.contact_id</code> guard is useless here: each worker checks its own snapshot, taken before the other one wrote anything. Classic check-then-act race.</p>
<p>The duplicates were not the only damage. The two events do not carry exactly the same data: in one case, the callback number dictated by the caller was only known to the first event, and the second event's commit, the last one, overwrote it with an empty value.</p>
<h2>Why not a unique constraint?</h2>
<p>The textbook answer is a unique index plus <code>INSERT … ON CONFLICT</code>. It did not fit well here:</p>
<ul>
<li>A contact's phone number is not unique in our data model: the same person can be stored with a mobile and a landline, and phone formats in old rows vary.</li>
<li>The real invariant is not "one contact per number", it is "<strong>one link per call</strong>": whichever event arrives second should reuse what the first one did.</li>
</ul>
<p>So the natural thing to serialize on is the <strong>call row</strong> itself.</p>
<h2>The fix: lock the call row</h2>
<p>Before deciding anything, the handler re-reads the call row with <code>SELECT … FOR UPDATE</code>. The second worker blocks on that read until the first one commits, then sees the committed <code>contact_id</code> and reuses it:</p>
<pre><code class="language-python">def link_inbound_caller(db: Session, call: Call) -&gt; None:
    if call.contact_id:
        return
    # Two events for the same call can arrive in the same millisecond on two
    # workers. Lock the call row: the second worker waits for the first commit,
    # then reads the contact it created instead of creating another one.
    locked = (
        db.query(Call.contact_id, Call.outcome_data)
        .filter(Call.id == call.id)
        .with_for_update()
        .first()
    )
    if locked is not None and locked.contact_id:
        call.contact_id = locked.contact_id
        # Keep data that only the other event knew about.
        committed = locked.outcome_data or {}
        current = call.outcome_data or {}
        if committed.get("callback_number") and not current.get("callback_number"):
            call.outcome_data = {**current, "callback_number": committed["callback_number"]}
        return

    contact = find_contact_by_phone(db, call.organization_id, call.caller_phone)
    if contact is None:
        contact = Contact(organization_id=call.organization_id, phone=call.caller_phone)
        db.add(contact)
        db.flush()
    call.contact_id = contact.id
</code></pre>
<p>A few details that matter:</p>
<ul>
<li><strong>The lock lives until the transaction ends.</strong> <code>with_for_update()</code> holds the row lock until commit or rollback, so the critical section is "read the call, find or create the contact, write <code>contact_id</code>, commit". Keep it short: no network calls, no <code>await</code> between the lock and the commit, or every concurrent event for that call will queue behind it.</li>
<li><strong>Re-read the columns you depend on.</strong> The ORM object <code>call</code> was loaded before the lock and is stale. We read <code>contact_id</code> and <code>outcome_data</code> again from the locked row and merge what the other event committed, instead of overwriting it.</li>
<li><strong>Lock order.</strong> If a handler locks several rows, always lock them in the same order (here, the call first) to avoid deadlocks between event types.</li>
</ul>
<h2>Testing it</h2>
<p>Unit tests with a single session never see this bug. Racing two threads and hoping they collide gives a flaky test. A deterministic version uses two real sessions against PostgreSQL and controls the interleaving:</p>
<pre><code class="language-python">def test_concurrent_webhooks_create_a_single_contact(call_id):
    db_a, db_b = SessionLocal(), SessionLocal()
    call_a = db_a.get(Call, call_id)
    call_b = db_b.get(Call, call_id)          # both see contact_id = None

    link_inbound_caller(db_a, call_a)         # A holds the row lock, not committed

    def second_webhook():
        link_inbound_caller(db_b, call_b)
        db_b.commit()

    t = threading.Thread(target=second_webhook)
    t.start()
    time.sleep(0.5)
    assert t.is_alive()                       # B is waiting for A's lock
    db_a.commit()
    t.join(timeout=10)

    assert call_b.contact_id == call_a.contact_id
    assert count_contacts(call_id) == 1
</code></pre>
<p>The <code>assert t.is_alive()</code> line is the interesting one: it proves the second event really waits for the first one instead of racing it. A second test does the same with different payloads and checks that the callback number known only to the first event survives the second commit.</p>
<h2>Takeaways</h2>
<ul>
<li>Webhooks are not ordered and not serialized. Two events about the same object can be processed concurrently, sometimes in the same millisecond.</li>
<li>A "has this already been done?" check is only safe if it is made under a lock (or enforced by a constraint).</li>
<li>Pick the lock that matches the real invariant. For us it was "one link per call", so the call row was the right thing to lock, not the contacts table.</li>
<li>When two events carry different parts of the data, the second writer must merge, not overwrite.</li>
</ul>
<p>We run this in production at <a href="https://voice-pilot.ai/">Voice Pilot</a>, an AI phone receptionist for French tradespeople and small businesses. If you handle telephony webhooks, it is worth checking your own "check then create" paths for the same pattern.</p>
]]></content:encoded></item></channel></rss>