# Building a call log and session chronicle with LiveKit and Hookdeck

LiveKit runs live voice sessions where people and AI agents share a room, such as voice games, interactive stories and classes led by an AI host. Apps like these keep a record of each session: who joined and left, which agent ran it and what audio played, which is what billing, attendance and music licensing reports come from. LiveKit sends each of those moments as a room webhook.

In this tutorial you build a call log from LiveKit room webhooks. LiveKit sends a webhook when a room starts, when each participant joins, drops or leaves, for each track and ingress, and when the room closes. The app turns them into one entry per room session, with who joined, who dropped, how long it ran and what played, plus a plain-sentence timeline of each session.

The webhooks go through [Hookdeck Event Gateway](/event-gateway) to an app on your machine. Event Gateway verifies LiveKit's token, drops repeated events and retries a delivery when the app fails, and the app verifies Hookdeck's signature on each delivery. To produce every kind of room event, the demo is The Drowned Bell, a voice adventure that two people can play together, run by two characters built on [LiveKit Agents](https://docs.livekit.io/agents/). The full code is in the [voice-adventure demo](https://github.com/hookdeck/hookdeck-demos/tree/main/livekit/voice-adventure) on GitHub.

## How the webhooks reach your app

**Diagram:** LiveKit sends a webhook for each room and participant event to an Event Gateway source. Event Gateway verifies LiveKit's token in the Authorization header, stores the event and answers 200, then delivers it to the deployed app over HTTPS. room_started opens the call, participant_joined and participant_left update the participants, and room_finished ends the call and gives its duration.

1. LiveKit sends a webhook for each room and participant event, and Event Gateway delivers each one to your app over HTTPS.
2. A room opens. LiveKit sends `room_started` to Event Gateway, which delivers it to your app over HTTPS. Event Gateway has verified LiveKit's token in the `Authorization` header, and the call is in progress.
3. A participant joins. `participant_joined` arrives the same way, and your app adds the participant to the call.
4. The participant leaves. `participant_left` is delivered, and your app marks them as left.
5. The room closes. `room_finished` is delivered, and the call log shows the call as ended, with its start, end and duration.

During development, the [Hookdeck CLI](/docs/cli) tunnels the webhooks to the app running on your machine. The diagrams in [How it works](#how-it-works) show that local setup.

LiveKit's [webhooks documentation](https://docs.livekit.io/intro/basics/rooms-participants-tracks/webhooks-events/) lists the events. The app uses these:

| Event | What it adds to the record |
| --- | --- |
| `room_started` | The session, with its start time |
| `participant_joined` | A participant and when they joined |
| `participant_connection_aborted` | A participant whose connection failed before it was established, shown as a drop in the chronicle |
| `participant_left` | When the participant left |
| `ingress_started`, `ingress_ended` | A soundtrack the app pulls into the room with the LiveKit Ingress API starting and ending. An ingress is a participant of kind `INGRESS` |
| `egress_started`, `egress_updated`, `egress_ended` | A recording and, when it ends, the file location |
| `room_finished` | The end time, and so the duration |

Every payload has an `id` (a UUID), a `createdAt` Unix timestamp in seconds and the `event` name. Room events add a `room` object, participant events add `participant`, and ingress and egress events add `ingressInfo` and `egressInfo`. LiveKit also sends `track_published` and `track_unpublished` when a participant starts or stops publishing audio. The call log ignores them.

The `participant.kind` field says who joined. It is absent for a player (LiveKit's `STANDARD`), `AGENT` for the story agent and `INGRESS` for a soundtrack. [Build the call log and the chronicle](#build-the-call-log-and-the-chronicle) uses it to tell them apart.

## What you'll need

* A [LiveKit Cloud](https://cloud.livekit.io) project with Inference credits, and an API key and secret. Inference usage beyond your plan's included credits is billed to the project, so keep test runs short.
* The [LiveKit CLI](https://docs.livekit.io/home/cli/) (`brew install livekit-cli`), signed in with `lk cloud auth --user-auth`, so setup can create the webhook for you
* A [Hookdeck](https://dashboard.hookdeck.com/signup) project, its project API key and its project signing secret
* Node.js 22.18 or later, and a browser with a microphone
* Three terminals, one each for the app, the agent and `hookdeck listen`

## Get it running {#get-it-running}

Clone the demo, add your keys, run setup, then start the app, the agent and `hookdeck listen`.

### Clone the demo and add your keys

```bash
git clone https://github.com/hookdeck/hookdeck-demos.git
cd hookdeck-demos/livekit/voice-adventure
npm install
cp .env.example .env

```

Add `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `HOOKDECK_API_KEY` and `HOOKDECK_SIGNING_SECRET` to `.env`. In LiveKit Cloud, the project's WebSocket URL, API key and secret are under **Settings, API keys**, and the secret is shown once. Event Gateway also uses the LiveKit API key and secret to verify LiveKit's token.

In the Hookdeck dashboard, open **Project settings**, then [**Secrets**](https://dashboard.hookdeck.com/settings/project/secrets), and copy the project API key and the project signing secret. Setup uses the API key to call the Hookdeck API. The app verifies the Hookdeck signature on each delivery with the signing secret and doesn't start without it.

### Run setup {#run-setup}

Sign in with the LiveKit CLI, then run setup:

```bash
lk cloud auth --user-auth
npm run setup

```

Setup creates the Event Gateway source, a CLI destination and the connection between them, and a webhook in your LiveKit Cloud project. To see each resource, read [Create the connection and the LiveKit webhook](#create-the-connection-and-the-livekit-webhook).

Setup writes the source URL to `LIVEKIT_WEBHOOK_URL` in `.env`, and running it again updates the same resources instead of adding new ones. It calls the API with `HOOKDECK_API_KEY`, so it doesn't touch your own `hookdeck login`.

The LiveKit Cloud webhook comes from LiveKit Cloud's management API, which takes your signed-in user session and not an API key and secret. The script reads the session that `lk cloud auth --user-auth` stores, or `LIVEKIT_SESSION_TOKEN` if you set it, and finds your project by matching `LIVEKIT_URL`. Set `LIVEKIT_PROJECT_ID` to choose a project yourself.

If you aren't signed in, setup still creates the Event Gateway connection and prints the dashboard steps. In the LiveKit Cloud dashboard, open **Settings, Webhooks** and select **Create new webhook**. Enter a name, paste the `LIVEKIT_WEBHOOK_URL` value as the URL, choose your API key as the **Signing API key** and select **Create**. **Actions, Send a test event** sends a test request.

### Start the app, the agent and hookdeck listen

Start each of these in its own terminal. `npm run listen` runs `hookdeck listen 4000 livekit-voice-adventure` with the Hookdeck CLI that `npm install` added to the demo. It logs the CLI in with your API key using its own config file, so your own `hookdeck login` stays as it is.

```bash
npm run listen   # hookdeck listen: forwards the source to localhost:4000
npm start        # the app and its page
npm run agent    # Hester and Old Bram (installs agent/ on the first run)

```

Open `http://localhost:4000`, optionally type a name, select **Join a call** and allow the microphone. The page asks the app for a token (`POST /api/token`). The server mints it with `livekit-server-sdk`, and it can join one room for 10 minutes, so the API secret never reaches the browser. The token also dispatches the story agent by name (`story-gm`), so only rooms joined from the page get a storyteller.

Hester Pennywhistle, the innkeeper, greets you, writes your name in her ledger and fetches Old Bram Tallow, who tells the story. You and any friends decide where the party goes, and the story ends when the Lantern of Hollow Mere is lit at the lighthouse. It runs about six minutes, and **Leave** stops it earlier.

Once you have joined, the page shows an invite link to your running story. A friend who opens it and selects **Join a call** joins the same room from their own microphone. The app only lets a browser join a room the app created that is still open.

While you play, the **Session chronicle**, the call log, the **Webhook deliveries** table and the **Data flow** pane fill in as the webhooks arrive.

## How it works {#how-it-works}

You first see what setup creates, then follow a webhook from LiveKit through signature verification to the call log and the chronicle, then deduplication, retries and replay, and end with event sizes and timing.

### Create the connection and the LiveKit webhook {#create-the-connection-and-the-livekit-webhook}

The setup script creates:

* a source named `livekit-voice-adventure`, of type `LIVEKIT`, which verifies LiveKit's token with your `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`
* a CLI destination named `local-livekit-voice-adventure` that forwards to `/webhooks/livekit` on your machine
* the connection between them, with a deduplicate rule and a retry rule
* a webhook in your LiveKit Cloud project named `Hookdeck: livekit-voice-adventure`, which sends events to the source URL and is signed with `LIVEKIT_API_KEY`

The Event Gateway part is one call to the [Hookdeck API](/docs/api), `PUT /connections`. It creates the connection, or updates it when one with that name exists, and creates the source and the CLI destination with it. The script sends it with a small `hookdeck()` helper, which sends each request with your project API key from `HOOKDECK_API_KEY` as a bearer token, so the call runs against the project the key belongs to:

```typescript
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 call includes the deduplication and retry rules, which [Deduplicate on the event id](#deduplicate-on-the-event-id) and [Retry failed deliveries, and replay](#retry-failed-deliveries-and-replay) explain. The source is part of the same call, with the LiveKit API key and secret in `config.auth` (the API requires them when it creates a `LIVEKIT` source, and the same call updates them when you run it again):

```typescript
const connection = await hookdeck('PUT', '/connections', {
  name: 'livekit-voice-adventure',
  source: {
    name: 'livekit-voice-adventure',
    type: 'LIVEKIT',
    config: { auth: { api_key: LIVEKIT_API_KEY, api_secret: LIVEKIT_API_SECRET } },
  },
  destination: { name: 'local-livekit-voice-adventure', type: 'CLI', config: { path: '/webhooks/livekit' } },
  rules: [
    // The same LiveKit event id inside 10 minutes is a duplicate. The API takes the window in milliseconds.
    { type: 'deduplicate', window: 600000, include_fields: ['body.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 },
  ],
});

```

The response's `connection.source.url` is the URL for the LiveKit webhook. `npm run setup` makes this call, then creates the LiveKit webhook.

Setup signs in to LiveKit Cloud to create that webhook, as [Run setup](#run-setup) describes.

### Verify Hookdeck's signature on the raw body {#verify-hookdecks-signature-on-the-raw-body}

LiveKit sends each webhook with `Content-Type: application/webhook+json`. The `Authorization` header holds a JWT signed with your API secret. Its `iss` claim is the API key and its `sha256` claim is the base64 SHA-256 hash of the body. The `LIVEKIT` source verifies that token with the API key and secret in the source's `config.auth`, so Event Gateway only creates an event for a request LiveKit signed.

Event Gateway then adds an `x-hookdeck-signature` header to each delivery. It is the base64 HMAC-SHA256 of the raw body, keyed with your project signing secret, so the app can check that the request came through your Event Gateway project. Hashing needs the exact bytes, so the endpoint reads the body raw instead of parsing it with `express.json()`:

```typescript
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);
}

app.post('/webhooks/livekit', express.raw({ type: '*/*', limit: '1mb' }), async (req, res) => {
  const raw_body: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');

  if (!verifyHookdeckSignature(raw_body, req.get('x-hookdeck-signature'), process.env.HOOKDECK_SIGNING_SECRET)) {
    return res.status(401).json({ error: 'invalid Hookdeck signature' });
  }

  const event = JSON.parse(raw_body.toString('utf-8')) as LiveKitEvent;
  applyEvent(log, event);
  applyChronicle(chronicle, event);
  res.json({ ok: true });
});

```

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. See [Hookdeck webhook signature verification](/docs/authentication#hookdeck-webhook-signature-verification) for the header format.

The signature has no timestamp. Event Gateway verified LiveKit's token when it accepted the request, so a retry after 10 minutes or a replay from the dashboard an hour later is a legitimate delivery, and it passes the check with the same signature.

To see what happens when LiveKit's token fails verification, follow [Send a badly signed request](#send-a-badly-signed-request).

### Build the call log and the chronicle {#build-the-call-log-and-the-chronicle}

Events can arrive out of order, and LiveKit documents that newer events wait for older ones to be delivered or abandoned. The call log still applies each event as an update to specific fields, keyed by the room's session id (`room.sid`), so the same event applied twice, or `participant_joined` arriving before `room_started`, leaves the log the same:

```typescript
export function applyEvent(log: CallLog, event: LiveKitEvent): ApplyResult {
  const created_ms = toMs(event.createdAt) ?? Date.now();
  const session = sessionFor(log, event.room, event.egressInfo?.roomName, event.egressInfo?.roomId);
  if (!session) return { duplicate: false };

  // A repeated event id is a duplicate delivery
  if (session.event_ids.includes(event.id)) return { duplicate: true, session_key: session.key };
  session.event_ids.push(event.id);

  const p = event.participant; // and entry is that participant's row in the session
  switch (event.event) {
    case 'room_finished':
      session.ended_at = max(session.ended_at, created_ms);
      break;
    case 'participant_joined':
      entry.joined_at = min(entry.joined_at, toMs(p.joinedAt) ?? created_ms);
      break;
    case 'participant_left':
      entry.left_at = max(entry.left_at, created_ms);
      break;
    // ...
  }
  return { duplicate: false, session_key: session.key };
}

```

Start times take the earliest value seen and end times take the latest, so the order the events arrive in doesn't matter. The duration is `ended_at - started_at`, computed when the call is listed. The full function is in `src/call-log.ts` in the demo, with tests that apply the same events forward, in reverse and with duplicates.

The session chronicle in `src/chronicle.ts` works the same way and adds the story. It tells the participants apart from the payload:

```typescript
switch (p.kind) {
  case 'AGENT': return 'gm';          // Hester, then Old Bram: one agent participant in the room
  case 'INGRESS': return 'soundtrack'; // a soundtrack pulled in by the app
}
// kind is absent for a player

```

Track events have no `kind`, so the chronicle reads participant events. A `participant_connection_aborted` event, or a disconnect reason of `CONNECTION_TIMEOUT` or `JOIN_FAILURE`, marks a player as dropped instead of left.

Each `ingress_started` and `ingress_ended` pair becomes a scene line with the soundtrack's duration. The timeline for a short session reads like this:

```text
The room opened
Pat joined
Hester and Old Bram joined
Scene 1, tavern: soundtrack started
Scene 1, tavern: soundtrack ended after 180 s
Sam dropped (connection timed out)
The session ended, 6 min 12 s long

```

The app also uses `ingress_ended` to restart a soundtrack while the story is still in that scene, because the files last 180 seconds and a scene can run longer. The app answers the webhook first and then does that work, so a slow ingress call can't turn into a failed delivery.

### Deduplicate on the event id {#deduplicate-on-the-event-id}

LiveKit's documentation says there are no guarantees around delivery, and that it retries a failed webhook request. Any sender that retries can deliver the same event twice, so the connection has a deduplicate rule on the LiveKit event id:

```json
{ "type": "deduplicate", "window": 600000, "include_fields": ["body.id"] }

```

The window is 10 minutes, in milliseconds. Event Gateway [deduplicates](/docs/deduplication) within a window of up to an hour. It still answers the repeat with a `200`, but it creates no event, so the app isn't called a second time.

**Diagram:** LiveKit sends the same room_finished webhook a second time. Event Gateway matches the body.id field inside the 10 minute window, drops the repeat, still answers 200, and forwards nothing to the app.

1. The app has handled this room's `room_finished`: the call is ended.
2. LiveKit sends the same `room_finished` again, because senders can deliver an event more than once.
3. Event Gateway sees the same `body.id` inside the 10 minute window and drops it. LiveKit still gets a 200.
4. Nothing is forwarded: the app is not called a second time and the call log stays as it was.

### Retry failed deliveries, and replay {#retry-failed-deliveries-and-replay}

The connection's retry rule is exponential, with 8 attempts starting at 30 seconds:

```json
{ "type": "retry", "strategy": "exponential", "count": 8, "interval": 30000 }

```

Event Gateway answers LiveKit as soon as it has stored the request, so LiveKit's own retries don't start because your app is slow or down. Event Gateway retries the delivery to your app instead.

**Diagram:** The app answers a delivery of room_finished with a 503. Event Gateway has already answered LiveKit with a 200, keeps the event and retries with exponential backoff, and the second attempt succeeds about 30 seconds later once the app recovers.

1. The app is down: it answers every delivery with a 503.
2. The room closes and LiveKit sends `room_finished`. Event Gateway stores it and answers LiveKit with a 200.
3. Event Gateway delivers it through `hookdeck listen`. Attempt 1 gets a 503 from the app.
4. 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.
5. The app recovers. Attempt 2 succeeds about 30 seconds later, and the event is delivered once.

Replay goes through Event Gateway, which keeps the original request. If the retries run out, or you want to run an event again after fixing the app, open it in the [dashboard](https://dashboard.hookdeck.com) and select **Retry**, or run:

```bash
hookdeck gateway event retry <event-id>

```

The replayed request has the same Hookdeck signature, so it passes the check in [Verify Hookdeck's signature on the raw body](#verify-hookdecks-signature-on-the-raw-body) however long after the original it arrives. See [retries](/docs/retries) and [event replay](/docs/events).

### Check the sizes and timing of the room webhooks

A 20 second call with two participants produced these webhooks:

| Event | Count | Body size |
| --- | --- | --- |
| `room_started` | 1 | 457 bytes |
| `participant_joined` | one per participant, including the agent and each soundtrack | about 760 bytes |
| `track_published`, `track_unpublished` | 2 each | 1.0 to 1.1 KB |
| `participant_left` | 2 | about 860 bytes |
| `room_finished` | 1 | 152 bytes |
| `ingress_started`, `ingress_ended` | 1 each per soundtrack | about 0.6 KB |

Events arrived in the order LiveKit generated them. The `room_finished` event arrived about 38 seconds after the last participant left, because the room waits out its departure and empty timeouts before it closes.

A record shouldn't assume a session ends when the last person leaves, and the chronicle closes about a minute after the last player is gone.

In the Hookdeck dashboard, each event shows the request LiveKit sent and each delivery attempt to your app. The **Data flow** pane at the bottom of the demo's page shows the same path live, and its other tabs play the duplicate, bad signature and app-down cases with captions.

## Try the failure cases {#try-the-failure-cases}

Run each case against the demo from [Get it running](#get-it-running), with `npm run listen`, `npm start` and `npm run agent` running.

### Send a badly signed request {#send-a-badly-signed-request}

**Diagram:** A request with a token signed by the wrong key reaches the Event Gateway source. Event Gateway accepts the request, then checks its token. The check of the Authorization header fails, so the request is recorded as VERIFICATION_FAILED and no event is created. The sender still gets a 200, and the app is never called.

1. A request claims to come from LiveKit, but its token was signed with the wrong key.
2. Event Gateway accepts the request, then checks its token.
3. Verification of `Authorization` fails. The request is recorded as `VERIFICATION_FAILED` and no event is created.
4. The sender still gets a 200, and your app is never called.

A request whose LiveKit token fails verification is rejected by Event Gateway. It is recorded as a request with the `VERIFICATION_FAILED` rejection cause, no event is created and the app isn't called. LiveKit still gets a `200`, so LiveKit's own retries don't start. To try it without a LiveKit room, `npm run simulate` sends events signed the way LiveKit signs them, and `--bad-signature` signs with the wrong secret:

```bash
npm run simulate -- room_finished --bad-signature

```

The Hookdeck dashboard lists the rejected request with its cause. A request that reaches the app without a valid `x-hookdeck-signature`, such as one sent straight to `localhost:4000`, gets the `401` from the handler in [Verify Hookdeck's signature on the raw body](#verify-hookdecks-signature-on-the-raw-body).

### Send a duplicate

To see the deduplication rule work, send the same event twice. The second request is listed in the Hookdeck dashboard without an event, and the app logs one delivery:

```bash
npm run simulate -- room_finished --twice

```

### Make a delivery fail

The page has a **Failure injection** panel that makes deliveries fail. Set **Fail the next** to `2`, select **Apply** and join a call. The app answers the next two deliveries with a `503`, Event Gateway keeps those events, and the first retry about 30 seconds later gets a `200`, so the call log updates late but correctly.

Set **Delay each answer (s)** to make the app slow instead, and the Hookdeck dashboard shows the attempt taking that long.

The **Webhook deliveries** table lists every request the app received with its event, size, the answer it gave and whether it was applied, a duplicate or rejected. The demo also appends each request to `data/deliveries.jsonl`, with the `Authorization` header stored as `[redacted]` because it is a bearer token.

## Going to production {#going-to-production}

* **A deployed app:** point the connection at an HTTP destination with your app's public URL, by updating the destination's type and URL or by creating a connection to a new HTTP destination. The endpoint and code stay the same, because the app already checks `x-hookdeck-signature` on every delivery. Set `HOOKDECK_SIGNING_SECRET` in the deployed app's environment.

### What to build next

* Record the room by starting a room composite egress with an output location you control (see LiveKit's [egress documentation](https://docs.livekit.io/home/egress/overview/)). When the recording ends, `egress_ended` includes the file's `location`, and the call log lists it under the session.

See the [voice-adventure demo](https://github.com/hookdeck/hookdeck-demos/tree/main/livekit/voice-adventure) for the full source, and [get started with Hookdeck](https://dashboard.hookdeck.com/signup).