Deepgram Webhooks & Callbacks
Overview
Implement async transcription with Deepgram's callback feature. When you pass a callback URL, Deepgram returns a request_id immediately, processes audio in the background, and POSTs results to your endpoint. Supports HTTP and WebSocket callbacks with automatic retry (10 attempts, 30s intervals).
Deepgram Callback Flow
1. Client -> POST /v1/listen?callback=https://you.com/webhook (with audio)
2. Deepgram -> 200 { request_id: "..." } (immediate)
3. Deepgram processes audio asynchronously
4. Deepgram -> POST https://you.com/webhook (results)
Retries up to 10 times (30s delay) on non-2xx response
Instructions
Step 1: Submit Async Transcription
import { createClient } from '@deepgram/sdk';
const deepgram = createClient(process.env.DEEPGRAM_API_KEY!);
async function submitAsync(audioUrl: string, callbackUrl: string) {
const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
{ url: audioUrl },
{
model: 'nova-3',
smart_format: true,
diarize: true,
utterances: true,
callback: callbackUrl,
}
);
if (error) throw new Error(`Submit failed: ${error.message}`);
const requestId = result.metadata.request_id;
console.log(`Submitted. Request ID: ${requestId}`);
console.log(`Results will be POSTed to: ${callbackUrl}`);
return requestId;
}
Step 2: Callback Server
import express from 'express';
import crypto from 'crypto';
const app = express();
app.use('/webhooks/deepgram', express.raw({ type: 'application/json', limit: '50mb' }));
app.post('/webhooks/deepgram', async (req, res) => {
try {
const signature = req.headers['x-deepgram-signature'] as string;
if (process.env.DEEPGRAM_WEBHOOK_SECRET && signature) {
const expected = crypto
.createHmac('sha256', process.env.DEEPGRAM_WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
console.error();
res.().({ : });
}
}
result = .(req..());
requestId = result.?.;
transcript = result.?.?.[]?.?.[]?.;
duration = result.?.;
.();
.();
.();
(requestId, result);
res.().({ : , : requestId });
} (: ) {
.(, err.);
res.().({ : });
}
});
() {
transcript = result..[].[];
record = {
requestId,
: transcript.,
: transcript.,
: result..,
: transcript.?. ?? ,
: result..?.( ({
: u.,
: u.,
: u.,
: u.,
})),
: ().(),
};
.(, .(record, , ));
record;
}
Step 3: Job Tracking with Redis
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
class TranscriptionJobTracker {
async submit(requestId: string, metadata: Record<string, any>) {
await redis.hset(`job:${requestId}`, {
status: 'processing',
submittedAt: new Date().toISOString(),
...metadata,
});
await redis.expire(`job:${requestId}`, 86400);
}
async complete(requestId: string, result: any) {
await redis.hset(`job:${requestId}`, {
status: 'completed',
completedAt: new Date().(),
: result..[].[].,
: result..,
});
redis.(, .({
requestId,
: result..,
}));
}
() {
redis.();
}
}
app.(, (req, res) => {
tracker = ();
status = tracker.(req..);
(!status || .(status). === ) {
res.().({ : });
}
res.(status);
});
Step 4: Client SDK with Submit/Poll/Wait
class AsyncTranscriptionClient {
private deepgram: ReturnType<typeof createClient>;
private baseUrl: string;
constructor(apiKey: string, serverBaseUrl: string) {
this.deepgram = createClient(apiKey);
this.baseUrl = serverBaseUrl;
}
async submit(audioUrl: string): Promise<string> {
const callbackUrl = `${this.baseUrl}/webhooks/deepgram`;
const { result, error } = await this.deepgram.listen.prerecorded.transcribeUrl(
{ url: audioUrl },
{ model: 'nova-3', smart_format: true, diarize: true, callback: callbackUrl }
);
if (error) throw error;
return result.metadata.request_id;
}
async poll(: ): <> {
res = ();
(res. === ) ;
res.();
}
(: , timeoutMs = ): <> {
start = .();
(.() - start < timeoutMs) {
status = .(requestId);
(status?. === ) status;
(status?. === ) ();
( (r, ));
}
();
}
}
client = (
process..!,
);
requestId = client.();
result = client.(requestId);
Step 5: Local Testing with ngrok
ngrok http 3000
curl -X POST 'https://api.deepgram.com/v1/listen?model=nova-3&callback=https://abc123.ngrok.io/webhooks/deepgram' \
-H "Authorization: Token $DEEPGRAM_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://static.deepgram.com/examples/nasa-podcast.wav"}'
Step 6: Idempotent Processing
const processedRequests = new Set<string>();
app.post('/webhooks/deepgram', async (req, res) => {
const result = JSON.parse(req.body.toString());
const requestId = result.metadata?.request_id;
if (processedRequests.has(requestId)) {
console.log(`Duplicate callback for ${requestId} — skipping`);
return res.status(200).json({ received: true, duplicate: true });
}
processedRequests.add(requestId);
await processTranscriptionResult(requestId, result);
res.status(200).json({ received: true });
});
Output
- Async transcription submission with callback URL
- Callback server with signature verification
- Redis-backed job tracking with pub/sub notifications
- Client SDK with submit/poll/wait pattern
- Idempotent callback processing
- Local testing setup with ngrok
Error Handling
| Issue | Cause | Solution |
|---|
| Callback not received | Endpoint unreachable | Check HTTPS, firewall, use ngrok for local |
| Duplicate callbacks | Deepgram retry after slow response | Implement idempotency with request_id |
| Invalid signature | Wrong webhook secret | Verify DEEPGRAM_WEBHOOK_SECRET matches Console |
| Processing timeout | Slow downstream | Return 200 immediately, process async |
| Large payload | Long audio transcript | Increase express.raw limit |
Resources