My Unique Index Decided Which Customer Owned Each Phone Call
VoiceDash is the client portal I build for voice AI agencies. An agency connects its Retell agents, and each of its clients logs in to see their own calls, transcripts and analytics. Every call is a row in a Conversation
VoiceDash is the client portal I build for voice AI agencies. An agency connects its Retell agents, and each of its clients logs in to see their own calls, transcripts and analytics. Every call is a row in a Conversation table, keyed by the call ID Retell gives it.
For months that key looked like the most obviously correct line in my schema:
model Conversation {
id String @id @default(cuid())
agentId String
platformCallId String @unique
// ...
}
A Retell call ID is globally unique. So the column is unique. What else would it be?
It turns out that one @unique was quietly answering a product question I had never asked: when the same phone agent is connected in two workspaces, which one owns the call? The database answered it for me: whoever stored it first. This post is about how that showed up, the fix, and the two things the fix still does not cover.
How one agent ends up in two workspaces
In a single-tenant app this never happens. In a multi-tenant one it happens more often than you would think. The commit message I wrote when I found it lists the three ways I could see:
- a new signup for an agency that had already tried VoiceDash under another account,
- a teammate creating their own workspace and connecting the same Retell agent,
- someone re-onboarding after deleting things.
In every case the Retell agent is one thing on Retell's side, and two Agent rows on mine, in two workspaces.
What the unique index did
Calls reach VoiceDash two ways. Retell posts a webhook when a call ends, and a sync job lists calls through the Retell API to fill in history and anything the webhook missed.
The sync step that stores a page of calls checked which call IDs already existed, across all agents:
const existing = await prisma.conversation.findMany({
where: { platformCallId: { in: usable.map((c) => c.call_id) } },
select: { platformCallId: true, agentId: true, duration: true },
});
If a call ID was already in the table, it was skipped. It did not matter that it belonged to a different agent in a different workspace. The insert would have failed on the unique index anyway, so skipping it looked like politeness, not a bug.
So the first workspace to import an agent's history kept all of it. The second workspace connected the same agent and got an empty-looking dashboard, then only the calls made after it took over the webhook. Nothing errored. Every query returned exactly what the schema said was true.
That is the part I keep thinking about. A constraint is usually described as protecting data. This one was making a business decision, "a call belongs to exactly one tenant, first come first served", and enforcing it more reliably than any of my actual business logic.
The fix: a call is unique per agent
The real rule is that each workspace keeps its own copy of every call its agent made. So uniqueness moves from the call to the pair:
model Conversation {
id String @id @default(cuid())
agentId String
platformCallId String
// ...
// One copy of a call per agent: a Retell agent connected in several
// workspaces shows its calls in every one of them.
@@unique([agentId, platformCallId])
@@index([platformCallId])
}
The plain index on platformCallId stays because there are still lookups by call ID alone.
Then every place that addressed a call by its ID had to say whose copy it meant. The webhook upsert:
await prisma.conversation.upsert({
where: { agentId_platformCallId: { agentId: agent.id, platformCallId: call.call_id } },
// ...
});
And the existence check in the sync, which now only counts this agent's copies:
const existing = await prisma.conversation.findMany({
where: { agentId, platformCallId: { in: usable.map((c) => c.call_id) } },
select: { platformCallId: true, duration: true },
});
The one I nearly missed was the AI analysis route. It looked up a conversation with findFirst({ where: { platformCallId: callId } }). After the change that query is not wrong in a way that throws. It just returns some workspace's copy of the call, possibly not the one that asked. It got agentId added to the filter. If you make this kind of change, grep for every findFirst and findUnique on the old key. The compiler catches the findUnique calls once the unique index is gone. It does not catch a findFirst.
Migrating a live table
The old index could not simply be swapped, because the running code still upserted on it. The migration is written to be re-runnable and was applied by hand in two steps around the deploy:
CREATE UNIQUE INDEX IF NOT EXISTS "Conversation_agentId_platformCallId_key"
ON "Conversation"("agentId", "platformCallId");
CREATE INDEX IF NOT EXISTS "Conversation_platformCallId_idx"
ON "Conversation"("platformCallId");
-- after the new code is live:
DROP INDEX IF EXISTS "Conversation_platformCallId_key";
UPDATE "Agent" SET "callsSyncedUntil" = NULL;
The last line matters more than it looks. Each agent has a sync watermark, and calls that had been skipped because another workspace owned them were already behind it. Resetting the watermark makes every agent read its history again, and the per-agent check means only the missing copies get inserted. It costs a full re-read of every history once, which is the price of letting a constraint be wrong for months.
One webhook URL, many workspaces
Fixing the table exposed the next shared resource. A Retell agent has exactly one webhook URL. When you connect an agent in VoiceDash, it sets that URL to point at your agent:
const webhookUrl = retellWebhookUrl(agent.id); // .../api/webhooks/retell?agentId=...
fetch(`https://api.retellai.com/update-agent/${platformAgentId}`, {
method: "PATCH",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ webhook_url: webhookUrl }),
}).catch(() => {});
So the most recently connected workspace gets live webhooks, and the others get each call from their automatic sync, through their own API key.
That leaves a hole on delete. If the workspace holding the webhook deletes its agent, Retell keeps posting to an agent that no longer exists and every other workspace drops back to sync only. So deleting an agent now runs a handoff in the background:
for (const next of candidates) { // same Retell agent, newest first
const apiKey = next.apiKey || (await workspaceRetellKey(next.workspaceId));
if (!apiKey) continue;
const res = await fetch(`${RETELL_API}/get-agent/${platformAgentId}`, { headers });
if (!res.ok) continue; // this workspace's key can't manage the Retell agent
const { webhook_url } = await res.json();
if (!String(webhook_url || "").includes(`agentId=${deletedAgentId}`)) return;
await fetch(`${RETELL_API}/update-agent/${platformAgentId}`, {
method: "PATCH",
headers,
body: JSON.stringify({ webhook_url: retellWebhookUrl(next.id) }),
});
return;
}
(workspaceRetellKey is my shorthand here for the inline lookup of the workspace's stored Retell integration.)
Two checks in there earn their place. A key from one workspace may not be able to manage an agent in another Retell account, so it reads the agent first and moves on if it cannot. And it only rewrites the URL if it still points at the deleted agent, so if someone set the webhook up somewhere else since, it is left alone.
What is still not right
I would rather list these than pretend the fix closed the topic.
Only the webhook holder gets the extras. AI summaries and evaluations are triggered from the Retell webhook route, and so is forwarding each call to the agency's own webhook URLs. The sync path stores calls and nothing else. So with one agent in two workspaces, the workspace that holds the webhook gets summaries and forwarded events, and the other gets the same calls with neither. The data is now shared fairly. The features on top of it are not. The fix is to run those side effects from wherever a call is first stored for an agent, not from the webhook handler.
Connecting silently takes the webhook. The connect code above PATCHes the URL without reading what was there, and swallows any error. A second workspace connecting an agent moves live delivery away from the first one and nobody is told. The handoff does not check whether the PATCH succeeded either. Both should at least record what happened.
Neither is fixed yet. They are next on the list, and writing this is how they got onto it.
The takeaway
When you add @unique to a column in a multi-tenant app, it is worth asking one question out loud: unique per what? A call ID is unique per Retell account. It is not unique per tenant of mine, because my tenants can overlap on the same upstream resource. The index was right about the world and wrong about my product.
If you are building anything that connects customers' third-party accounts, the same shape shows up everywhere: one Stripe account in two workspaces, one Slack channel installed twice, one phone number behind two portals. Somewhere in your schema there is probably a unique index that has already decided who owns it.
I wrote about the sync side of this, watermarks and why a webhook is never the whole history, in A Webhook Tells You Something Happened, Not That You Have Everything. VoiceDash itself is at voice-dash.com.
How do you handle this one? When two of your tenants connect the same upstream resource, do you give each a copy, or pick an owner and make the other one ask?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.