Building outbound lead calling with Retell AI and Hookdeck
Property agencies try to call a new enquiry back within minutes, and some now have a Retell AI voice agent make that call. Afterwards the app has to act on how the call went, by booking a viewing, ringing again later or updating the CRM. Retell reports how the call went in webhooks.
In this tutorial you build an app that has a Retell AI voice agent call each new lead from a property website, then tracks the call through Retell's webhooks. Retell sends call_started, call_ended and call_analyzed for every call, and the app uses them to update the lead's status and store the call summary and the details Retell extracted.
A missed call_ended leaves a lead stuck on Calling, and a repeated one can trigger the same follow-up twice. Hookdeck Event Gateway verifies the X-Retell-Signature, drops duplicates and retries a delivery when your app fails. The full code is in the outbound-lead-calling demo on GitHub.
How the webhooks reach your app
A lead arrives and the app starts a call through Retell's API. Retell posts call_started to an Event Gateway source when the call connects, then call_ended and call_analyzed together when it ends. Event Gateway verifies and stores each one and delivers it to the deployed app over HTTPS, signed with its own signature, which the app verifies. The app moves the lead from Calling to In call, Call ended and Analyzed.
- Your app starts calls through Retell's API, and Retell reports each call back through Event Gateway, which delivers to your app over HTTPS.
- A lead arrives and your app creates the call through Retell's API. The lead is Calling.
- The call connects. Retell sends
call_started(1.5 KB) to Event Gateway, which delivers it to your app over HTTPS and signs the delivery. Your app verifies the Hookdeck signature. The lead is In call. - When the call ends, Retell sends
call_ended(2.8 KB) andcall_analyzedtogether.call_endedis delivered first: the lead is Call ended. -
call_analyzed(3.1 KB) follows straight behind it with the summary. The lead is Analyzed.
During development, the Hookdeck CLI tunnels the webhooks to the app running on your machine. The diagrams in How it works show that local setup.
Every Retell webhook has an event field and a call object. The call.call_id field identifies the call in all three events, and call.metadata holds whatever your app attached when it started the call.
| Event | Contains |
|---|---|
call_started | The call object: call_id, call_type, agent_id, metadata and the dynamic variables |
call_ended | The same, plus disconnection_reason, timestamps, duration and the transcript |
call_analyzed | The same, plus call_analysis: call_summary, user_sentiment, call_successful and custom_analysis_data |
A call that never connects, such as an unanswered, busy or failed dial, sends call_ended and call_analyzed without call_started. See the Retell webhook documentation for the payloads, and the guide to Retell AI webhooks for the full reference.
What you'll need
- A Retell AI account with an API key, a public key and a webhook key (the webhook key can be the same key as the API key)
- A Hookdeck account, a project API key and the project signing secret
- Node.js 22 or later, and a microphone for the browser call
Get it running
Clone the demo, add your keys, choose the webhook key in Retell, run setup, then start the app and make a call.
Clone the demo and add your keys
Clone the demo and install it:
git clone https://github.com/hookdeck/hookdeck-demos.git
cd hookdeck-demos/retell/outbound-lead-calling
npm install
cp .env.example .env
Add these keys to .env:
RETELL_API_KEY: in the Retell dashboard, open Settings, then API Keys, and copy an API key (manage API keys). Setup uses it to create the Retell LLM and the agent, and the app uses it to start calls.RETELL_PUBLIC_KEY: in the Retell dashboard, open API Keys, then Public Keys, create a key, addlocalhostto its allowed domains and copy the value, which starts withpublic_key_(public keys). The browser call uses it.RETELL_SECRET_KEY: the webhook key, which is the one API key marked as the webhook key under Settings, then API Keys. Add it only if that is a different key fromRETELL_API_KEY. See Set the webhook key in Retell for how to choose it.HOOKDECK_API_KEY: in the Hookdeck dashboard, open Project settings, then Secrets, and copy the project API key. Setup uses it to call the Hookdeck API.HOOKDECK_SIGNING_SECRET: copy the project signing secret from the same page. The app uses it to verify thex-hookdeck-signatureheader on each delivery, and it won't start without it.
Set the webhook key in Retell
Retell has no separate webhook secret. It signs every webhook with the one API key that has the webhook badge in the dashboard.
To choose that key, open Settings, then API Keys, and select Set as Webhook Key (manage API keys). Only one key can be the webhook key at a time, and any other key fails verification.
Run setup
Run npm run setup. It creates the Event Gateway connection, gives its source the webhook key, then creates the Retell LLM and agent and writes their IDs to .env. Running it again updates the same source, destination and connection.
npm run setup
To see the code, read Create the Event Gateway connection and turn on verification.
Start the app and make a call
Start hookdeck listen and the app in two terminals. npm run listen runs the Hookdeck CLI, which npm install added to the demo. It logs the CLI in with HOOKDECK_API_KEY, using its own config so your own hookdeck login isn't changed, then runs hookdeck listen 4000 retell-call-events.
npm run listen
npm start
Open http://localhost:4000. Sam, the Acme Realty caller, calls the lead named in the enquiry form, and you answer as that lead. Change the name or property if you like, then select Have Sam call Alex (the button uses the name in the form).
Allow the microphone, and answer Sam with a budget, a move-in date and a day for a viewing. Hang up, or let the agent end the call.
The lead moves through Calling, In call, Call ended and Analyzed, with each webhook on its timeline. When call_analyzed arrives, the lead shows the summary and the extracted budget, move-in timeline and viewing preference.
The Data flow pane at the bottom of the page shows each message live. It starts with the app's request to Retell, then each webhook as it moves from Retell through Event Gateway and hookdeck listen to the app. Select a message to see whether it verified, each delivery attempt and what the app answered, with a View in Hookdeck link.
A request that failed verification shows as rejected, with no event and no delivery.
How it works
You first see what npm run setup creates, then follow a webhook from Retell through signature verification to the lead's status, and end with the retry for an unanswered call, deduplication and delivery retries.
Create the Event Gateway connection and turn on verification
npm run setup creates the Event Gateway connection first, because the Retell agent needs the source URL, and then creates the agent, as Create the Retell agent describes. Setup calls the Hookdeck API with a small hookdeck() helper, which sends each request with your project API key from HOOKDECK_API_KEY as a bearer token:
const HOOKDECK_API_BASE = 'https://api.hookdeck.com/2026-09-01';
async function hookdeck(method: string, route: string, body?: unknown) {
const response = await fetch(`${HOOKDECK_API_BASE}${route}`, {
method,
headers: { authorization: `Bearer ${process.env.HOOKDECK_API_KEY}`, 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
if (!response.ok) throw new Error(`Hookdeck API ${method} ${route} -> ${response.status}: ${text.slice(0, 300)}`);
return text ? JSON.parse(text) : undefined;
}
The connection has the deduplication and retry rules, which Deduplicate on the event and the call ID and Retry failed deliveries explain, and a CLI destination that delivers to your machine through hookdeck listen:
const flow = {
name: 'retell-call-events',
cliPath: '/webhooks/retell',
rules: [
// Same event for the same call within 10 minutes is a duplicate. The API takes the window in milliseconds.
{ type: 'deduplicate', window: 600000, include_fields: ['body.event', 'body.call.call_id'] },
// If the app is down or erroring, retry for about two hours (30s, 60s, 2m, 4m, ...)
{ type: 'retry', strategy: 'exponential', count: 8, interval: 30000 },
],
};
PUT /connections creates or updates the source, the destination and the rules, matching them by name. The source uses the RETELL source type, so Event Gateway knows how Retell signs requests. The response holds the source URL, which becomes the agent's webhook_url.
A second call, PUT /sources, gives the source the webhook key Retell signs with. The key is in the RETELL_SECRET_KEY environment variable, or RETELL_API_KEY if that is the webhook key:
const connection = await hookdeck('PUT', '/connections', {
name: flow.name,
source: { name: flow.name, type: 'RETELL' },
destination: { name: `local-${flow.name}`, type: 'CLI', config: { path: flow.cliPath } },
rules: flow.rules,
});
await hookdeck('PUT', '/sources', {
name: flow.name,
type: 'RETELL',
config: { auth: { webhook_secret_key: RETELL_SECRET_KEY } },
});
const events_url = connection.source.url;
npm run setup runs this code and then creates the Retell LLM and agent.
The X-Retell-Signature header has the form v=<timestamp>,d=<digest>, where the digest is an HMAC-SHA256 of the raw body followed by the timestamp. Event Gateway checks it on every request to the source URL. See how to secure and verify Retell AI webhooks with Hookdeck for the details.
To see what happens when that check fails, follow Send a badly signed request.
Create the Retell agent
With the connection in place, setup creates a Retell LLM and an agent named "Acme Realty lead caller (Hookdeck demo)" and writes their IDs to .env. It doesn't change your other agents. The prompt uses dynamic variables, which the app fills in for each lead when it starts the call:
const llm_body = {
general_prompt: `You are Sam, a friendly assistant at Acme Realty. You are making an outbound call
to a lead who just asked about a property on the Acme Realty website.
Lead name: {{lead_name}}
Property they asked about: {{property_interest}}
What they wrote on the form: {{lead_notes}}
...`,
begin_message: 'Hi, is that {{lead_name}}?',
start_speaker: 'agent',
general_tools: [{ type: 'end_call', name: 'end_call', description: 'End the call when the conversation is finished.' }],
};
The agent decides where the webhooks go and what Retell extracts after the call:
const agent_body = {
agent_name: 'Acme Realty lead caller (Hookdeck demo)',
voice_id: 'retell-Cimo',
response_engine: { type: 'retell-llm', llm_id },
webhook_url: events_url, // the Event Gateway source URL from the connection
webhook_events: ['call_started', 'call_ended', 'call_analyzed'],
post_call_analysis_data: [
{ type: 'string', name: 'budget', description: "The lead's budget, if they gave one." },
{ type: 'string', name: 'move_in_timeline', description: 'When the lead wants to move.' },
{ type: 'boolean', name: 'viewing_requested', description: 'True if the lead agreed to or asked for a viewing.' },
{ type: 'string', name: 'preferred_viewing_time', description: 'The viewing day or time the lead preferred.' },
],
};
An agent's webhook_url replaces the account-level webhook for that agent's calls, so the demo doesn't change where your other agents send events. The post_call_analysis_data fields come back in call_ on the call_analyzed webhook.
Start the call from the browser
The demo starts each call in the browser, so you can talk to the agent without buying a phone number. The page uses RetellClient from Retell's web SDK (retell-client-js-sdk 3.x) with a public key, which is meant for browser code. Your API key stays on the server.
When the lead submits the form, the server creates the lead and returns the agent, the dynamic variables for the prompt and metadata.lead_id, which the page passes to Retell.
app.post('/api/web-leads', (req, res) => {
const lead_id = randomUUID().replace(/-/g, '').slice(0, 12);
addLead({ id: lead_id, name, property_interest, notes, status: 'new', /* ... */ });
res.status(201).json({
id: lead_id,
agent_id: RETELL_AGENT_ID,
retell_llm_dynamic_variables: { lead_name: name, property_interest, lead_notes: notes || 'none' },
metadata: { lead_id },
});
});
The page then starts the call:
const { RetellClient } = await import('https://esm.sh/retell-client-js-sdk@3.0.4?deps=livekit-client@2.24.0,eventemitter3@5.0.4');
const client = new RetellClient({ key: config.retell_public_key });
const session = client.createWebCall({
agent_id: lead.agent_id,
retell_llm_dynamic_variables: lead.retell_llm_dynamic_variables,
metadata: lead.metadata,
hooks: {
onStatus: (state) => { /* 'live', then 'ended' */ },
onError: (error) => { /* show it */ },
},
});
await session.ready;
The deps query pins the SDK's dependencies, so a new release of one of them can't change what the page loads.
Retell copies metadata into every webhook for the call, so the handler finds the lead from call.metadata.lead_id, even if a webhook arrives before the page has reported the call_id. See web call in the Retell docs.
A phone call sends the same three webhooks. To call the lead's phone instead, the page's Submit enquiry and have Sam call button makes the server call Retell's create phone call API with a Retell number, the same dynamic variables and the same metadata. The demo README covers the optional phone call setup.
Verify Hookdeck's signature on each delivery
Event Gateway signs every delivery to your app with an x-hookdeck-signature header, which is the base64 HMAC-SHA256 of the raw request body, keyed with the project signing secret from HOOKDECK_SIGNING_SECRET. The app checks it before any handler runs, so a request that didn't come from Event Gateway never reaches the lead. See Hookdeck webhook signature verification for the header format.
The signature has no timestamp. Event Gateway verified Retell's X-Retell-Signature when it accepted the request, so a retry or a replay hours later is a legitimate delivery and still passes.
The verify function recomputes the signature from the raw body and compares it with the header after a length check, because timingSafeEqual throws on inputs of different lengths:
import { createHmac, timingSafeEqual } from 'crypto';
function verifyHookdeckSignature(raw_body: Buffer, signature_header: string | undefined, secret: string | undefined): boolean {
if (!secret || !signature_header) return false;
const expected = Buffer.from(createHmac('sha256', secret).update(raw_body).digest('base64'), 'utf8');
const received = Buffer.from(signature_header, 'utf8');
// timingSafeEqual throws when the lengths differ, so check the length first
return expected.length === received.length && timingSafeEqual(expected, received);
}
While you roll the signing secret, Event Gateway also sends x-hookdeck-signature-2, signed with the previous secret. The demo's src/hookdeck-signature.ts accepts either header.
The signature covers the exact bytes Event Gateway sent, so the app keeps the raw body while Express parses the JSON. A middleware then answers 401 when the header is missing or wrong:
app.use(express.json({ limit: '5mb', verify: (req: any, _res, buf) => { req.raw_body = Buffer.from(buf); } }));
function requireHookdeckSignature(req: Request, res: Response, next: NextFunction) {
const raw_body: Buffer = (req as any).raw_body ?? Buffer.alloc(0);
if (verifyHookdeckSignature(raw_body, req.header('x-hookdeck-signature'), process.env.HOOKDECK_SIGNING_SECRET)) return next();
res.status(401).json({ error: 'invalid Hookdeck signature' });
}
Update the lead from the call events
The handler is registered behind the middleware and applies the verified, deduplicated event to the lead:
app.post('/webhooks/retell', requireHookdeckSignature, (req, res) => {
try {
const result = applyRetellEvent(req.body, { hookdeck_event_id: req.header('x-hookdeck-eventid') });
if (result === 'invalid') return res.status(400).json({ error: 'not a Retell call event' });
res.sendStatus(200);
} catch (error) {
res.sendStatus(500); // Event Gateway retries the delivery
}
});
The status code tells Event Gateway whether the delivery worked. Any response other than a 2xx counts as a failed attempt, including the 401 for a bad signature, so the connection's retry rule retries it, as in Retry failed deliveries.
A 500 or 503 usually clears on a retry. A 400 for a body the app can't apply as a call event fails the same way every time, and its attempts in the dashboard show why.
The demo answers 200 for an event whose lead it can't find, because a retry wouldn't find the lead either.
applyRetellEvent looks up the lead from call.metadata.lead_id and moves it forward:
switch (event) {
case 'call_started':
updateLead(lead.id, { call_id: call.call_id, status: advance(lead, 'in_call') });
break;
case 'call_ended':
updateLead(lead.id, {
call_id: call.call_id,
status: advance(lead, endStatus(call.disconnection_reason)),
disconnection_reason: call.disconnection_reason,
duration_seconds: Math.round((call.end_timestamp - call.start_timestamp) / 1000),
...planRetry(lead.attempt, call.disconnection_reason),
});
break;
case 'call_analyzed':
updateLead(lead.id, {
status: advance(lead, 'analyzed'),
summary: call.call_analysis?.call_summary,
call_successful: call.call_analysis?.call_successful,
analysis: call.call_analysis?.custom_analysis_data,
});
break;
}
In real traffic, events arrive out of order, some calls never connect, and events repeat. The demo handles all three:
- Order doesn't matter.
advanceonly moves a lead forward (Calling, In call, Call ended, Analyzed), so a latecall_startedaftercall_endeddoesn't move it back. In the demo's test calls,call_endedandcall_analyzedarrived at the same moment for a short call. - A call that never connected still ends cleanly. These
disconnection_reasonvalues mean the call did not connect:dial_failed,invalid_destination,user_declinedand telephony errors (see debug call disconnection).endStatusmaps them to Failed, so the lead doesn't wait for acall_startedthat never comes. Onlydial_no_answer,dial_busyandvoicemail_reachedmean the lead didn't pick up, and only those map to No answer and are retried. - Repeats and old calls change nothing. The app records each event it applied, with its
call_id, on the lead's timeline. It ignores a repeat of the same event for the same call, and ignores an event from an older call of the same lead, so a replay from the Hookdeck dashboard or a late event from an earlier attempt leaves the lead unchanged.
Retry a call the lead didn't answer
When call_ended has a no-answer, busy or voicemail reason, planRetry schedules the next attempt, up to 3 attempts in all, and the lead shows a countdown to it. After the last miss, the lead reads Gave up. A call that connected, or failed, schedules nothing.
The demo doesn't dial by itself. When the countdown ends, the page re-arms the call button so the next click rings the lead again. A production app needs a scheduler or queue (a delayed job, or a sweep over the next attempt time) that places the call from the server, survives a restart and respects calling hours and consent.
Deduplicate on the event and the call ID
Retell retries a webhook up to three times when it doesn't get a 2xx within 10 seconds, so the same event can arrive more than once. The three events for one call share a call_id, so deduplicating on the call ID alone would drop call_ended after call_started arrived. The deduplication rule uses the event name and the call ID together:
{ type: 'deduplicate', window: 600000, include_fields: ['body.event', 'body.call.call_id'] }
The signature covers a timestamp, so a request that is sent again later can have a different X-Retell-Signature. That is why the rule compares named fields and not the whole request. The window is 10 minutes (600000 milliseconds). Event Gateway deduplicates within a window of 1 second to 1 hour.
The window only covers repeats that arrive close together, so the app keeps its own check as well. It ignores a repeat of the same event for the same call, and an event from an older call of the same lead. A replay from the dashboard after the window has passed leaves the lead unchanged for the same reason.
Retell sends the same call_ended webhook a second time. Event Gateway matches the event name and call ID inside the 10 minute window, drops the repeat, still answers 200, and forwards nothing to the app.
- The app has handled this call's
call_ended: the lead is Call ended. - Retell sends the same
call_endedagain, because senders can deliver an event more than once. - Event Gateway sees the same
body.event + body.call.call_idinside the 10 minute window and drops it. Retell still gets a 200. - Nothing is forwarded: the app is not called a second time and the lead stays as it was.
Retry failed deliveries
The connection also has a retry rule, up to eight retries with exponential backoff, the first 30 seconds after the failed attempt.
{ type: 'retry', strategy: 'exponential', count: 8, interval: 30000 }
Event Gateway answers Retell as soon as it has stored the request, so Retell's own retries don't start because your app is slow or down. Event Gateway retries the delivery to your app instead.
The app answers a delivery of call_ended with a 503. Event Gateway has already answered Retell with a 200, keeps the event and retries with exponential backoff, and the second attempt succeeds about 30 seconds later once the app recovers.
- The app is down: it answers every delivery with a 503.
- The call ends and Retell sends
call_ended. Event Gateway stores it and answers Retell with a 200. - Event Gateway delivers it through
hookdeck listen. Attempt 1 gets a 503 from the app. - Event Gateway keeps the event and retries with exponential backoff: the first retry is 30 seconds after the failed attempt, then it waits longer each time, up to 8 retries.
- The app recovers. Attempt 2 succeeds about 30 seconds later, and the event is delivered once.
If you exhaust the retries, open the event in the Hookdeck dashboard and retry it once the app is fixed. See retries and event replay.
Check the sizes of the three call webhooks
These are the request bodies Event Gateway delivered for a nine second web call in the demo's test:
| Webhook | Body size |
|---|---|
call_started | about 1.5 KB |
call_ended | about 2.8 KB |
call_analyzed | about 3.1 KB |
call_ended and call_analyzed include the transcript, so they grow with the length of the call.
Try the failure cases
Run each case against the demo from Get it running, with npm run listen and npm start running.
Send a badly signed request
A request with a signature that doesn't verify gets a 200 response, so the sender sees nothing unusual. Event Gateway records the request as rejected with the cause VERIFICATION_FAILED and creates no event, so nothing reaches your app. Check the request list in the Hookdeck dashboard, and not the response status, to see whether a request verified.
A request signed with the wrong key reaches the Event Gateway source. Event Gateway accepts it, fails the x-retell-signature check, records VERIFICATION_FAILED, creates no event and still answers 200, so the app is never called.
- A request claims to come from Retell, but its signature was made with the wrong key.
- Event Gateway accepts the request, then checks its signature.
- Verification of
x-retell-signaturefails. The request is recorded asVERIFICATION_FAILEDand no event is created. - The sender still gets a 200, and your app is never called.
The demo's npm run probe sends one correctly signed request and one badly signed request to the source, then reads both outcomes back from Event Gateway's request records. The first shows verified: true, and the second shows verified: false with VERIFICATION_FAILED. If a real call's webhooks show VERIFICATION_FAILED, the key on the source isn't the webhook key, so fix .env and run npm run setup again.
Event Gateway verifies Retell's signature when it accepts each request, and the app verifies Event Gateway's x-hookdeck-signature on each delivery, as in Verify Hookdeck's signature on each delivery. A request sent straight to the app, without a valid Hookdeck signature, gets a 401.
Send a duplicate
Run npm run simulate -- call_ to see the deduplication rule work without a call. It sends the same signed call_ended twice. Event Gateway accepts both requests, shows the second as ignored, and the app receives one delivery.
Make a delivery fail
Open http://localhost:4000, set Fail the next to 1 delivery, select Apply and make a call as in Start the app and make a call. The next delivery gets a 503, and the retry 30 seconds later gets a 200 and updates the lead.
Simulate a lead who doesn't answer
To try the no-answer retry without a call, select Lead does not answer. The page sends a signed no-answer call_ended event through the Event Gateway source, and the lead gets its next attempt and countdown.
Going to production
- Protect the public key: in the public key's settings, allow only domains you control, and enable reCAPTCHA v3 to limit automated abuse. Once reCAPTCHA is on, creating a web call needs a valid reCAPTCHA token
- Storage: replace the JSON file with your database, and enqueue follow-up work, such as booking the viewing, instead of doing it in the handler
- Fan-out: add a second connection on the same source, with a filter on
body.event, to sendcall_analyzedevents to your CRM
Read the guide to Retell AI webhooks for the reference, try the local testing guide, and get started with Hookdeck.