# Guide to Medplum Webhooks: Features and Best Practices

Medplum is an open-source platform for building clinical software on FHIR, available as a hosted service or self-hosted. Instead of a webhook settings page, it uses the FHIR standard's own mechanism: a `Subscription` resource with a `rest-hook` channel. When a resource matching the subscription's criteria is created, updated or deleted, Medplum posts it to your endpoint, which lets an integration engine, a lab system or your own backend react to clinical data as it changes.

This guide shows how to write a Medplum rest-hook Subscription, what a notification contains, how to turn on and verify `X-Signature`, and how to size the retry policy for the downtime you need to survive.

## What are Medplum webhooks?

A Medplum webhook is an active FHIR `Subscription` with `channel.type` set to `rest-hook`, a `channel.endpoint` URL and `criteria` in FHIR search syntax, such as `Patient` or `DiagnosticReport?status=completed`. You create it with the FHIR API or in the Medplum App, like any other resource.

Medplum adds behaviour through extensions on the Subscription: which interactions trigger it, a signing secret, the number of attempts, which status codes count as success, and where audit records go. These extensions are Medplum-specific and won't carry over to other FHIR servers.

## Medplum webhook features

| Feature | Details |
| --- | --- |
| Signature | hex HMAC-SHA256 |
| Signature header | `x-signature` |
| Body | JSON |

From Medplum's [subscription extensions documentation](https://www.medplum.com/docs/subscriptions/subscription-extensions):

* Signing is off until you add the `subscription-secret` extension.
* **Attempts:** 4 by default, adjustable from 1 to 18 with `subscription-max-attempts`.
* **Backoff:** about 20 seconds before the first retry, doubling each time up to an 8-hour cap.
* **Success codes:** set with `subscription-success-codes`.
* **History:** every attempt is recorded as an `AuditEvent`.

## Events and payloads

Medplum has no event names. A Subscription fires on create, update and delete by default, and `subscription-supported-interaction` extensions limit it to the interactions you list:

```json
{
  "resourceType": "Subscription",
  "status": "active",
  "criteria": "Patient",
  "channel": {
    "type": "rest-hook",
    "endpoint": "https://example.com/webhooks/medplum"
  },
  "extension": [
    { "url": "https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction", "valueCode": "create" },
    { "url": "https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction", "valueCode": "update" }
  ]
}

```

For creates and updates, the body is the resource itself, identified by its `resourceType` and `id`. Medplum's docs don't show a delivered body, and nothing in it says whether the resource was created or updated. If you need to tell them apart, use one Subscription per interaction with a different endpoint path for each.

Deletes are different. The body is an empty `{}`, and the deleted resource's type and ID arrive in the `X-Medplum-Deleted-Resource` header. The HMAC covers only the body, so that header isn't signed. Check it against your own records before acting on it.

## Setting up Medplum webhooks

1. Choose a strong random secret and store it as `MEDPLUM_SUBSCRIPTION_SECRET`.
2. Create a Subscription with `status: active`, your `criteria`, `channel.type: rest-hook` and `channel.endpoint`, for example `https://example.com/webhooks/medplum`.
3. Add the signing extension: `https://www.medplum.com/fhir/StructureDefinition/subscription-secret` with `valueString` set to your secret.
4. Add `subscription-max-attempts` if 4 attempts over about 2 minutes isn't enough.

Add a subscription-secret extension to the Medplum Subscription. Without it, deliveries are unsigned and fail verification.

With Hookdeck, create a Medplum source with the same secret and use the source URL as `channel.endpoint`. If a Subscription has no secret, leave verification off on the source, since there's no signature to check. To test against a local server:

```bash
npx hookdeck-cli listen 3000 medplum --path /webhooks/medplum

```

Then create or edit a resource that matches the criteria, and check `/Subscription/<id>/event` in the Medplum App for the `AuditEvent`.

## Securing Medplum webhooks

With the secret extension in place, `X-Signature` carries a hex HMAC-SHA256 of the request body, keyed with the `valueString`. Compute the HMAC over the raw bytes and compare in constant time. Medplum's [signature section](https://www.medplum.com/docs/subscriptions/subscription-extensions#signatures) has a TypeScript example that hashes `JSON.stringify(req.body)`, which can produce different bytes from those Medplum signed. Its Python example reads the raw body, which is the safer approach.

### Node.js verification

```javascript
const crypto = require('node:crypto');

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const signature = headers['x-signature'];
  if (typeof signature !== 'string') return false;
  const key = Buffer.from(secret, 'utf8');
  const message = rawBody;
  const candidates = [signature];
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
    const received = Buffer.from(candidate, 'hex');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

```

The handler treats an empty body as a deletion and records everything else as the resource's latest version:

```javascript
const express = require('express');

const app = express();

app.post('/webhooks/medplum', express.raw({ type: '*/*' }), async (req, res) => {
  const secret = process.env.MEDPLUM_SUBSCRIPTION_SECRET;
  if (!secret) return res.sendStatus(500);
  if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);

  let resource;
  try {
    resource = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.sendStatus(400);
  }
  if (!resource || typeof resource !== 'object' || Array.isArray(resource)) return res.sendStatus(400);
  try {
    if (!resource.resourceType) {
      await queueDeletionCheck(req.get('x-medplum-deleted-resource'));
      return res.sendStatus(200);
    }

    await upsertFhirResource(resource.resourceType, resource.id, resource.meta?.versionId, resource);
  } catch {
    return res.sendStatus(503);
  }

  res.sendStatus(200);
});

```

`upsertFhirResource` ignores a version it has already stored, which absorbs retries. `queueDeletionCheck` confirms the deletion with the Medplum API before removing anything, since the header isn't covered by the signature.

No timestamp is signed. Hookdeck's Medplum source verifies the same HMAC, answers Medplum with `200`, and records a mismatch as failed verification.

> **Make Medplum webhooks production-ready.** [Hookdeck Event Gateway](/event-gateway) accepts each Medplum notification immediately and retries your integration for as long as your policy allows, instead of the 2 minutes Medplum gives you by default.

## Medplum webhook limitations and pain points

### The default retry window is about 2 minutes

**The Problem:** A short maintenance window on your side loses notifications.

**Why It Happens:** By default Medplum makes 4 attempts, which are exhausted in roughly 2 minutes. After the last one, the notification is dropped and not queued.

**Workarounds:**

* Raise `subscription-max-attempts`: 12 covers about 11 hours, and the maximum of 18 about 2.5 days.
* For high-volume subscriptions, pair longer retries with the log-only `AuditEvent` destination to limit database growth, as Medplum suggests.

**How Hookdeck Can Help:** Hookdeck acknowledges the first attempt and holds the notification, with retries and replay on your terms.

### Signing is opt-in

**The Problem:** A Subscription created without the secret extension sends unsigned requests.

**Why It Happens:** HMAC signing is enabled only by the `subscription-secret` extension.

**Workarounds:**

* Add the extension to every rest-hook Subscription, ideally enforced in the code that creates them.
* Reject unsigned requests at the receiver.

**How Hookdeck Can Help:** A Hookdeck source with verification enabled records unsigned or wrongly signed requests as failed verification, which makes a Subscription missing its secret easy to spot.

### Deletes and updates are hard to read

**The Problem:** Creates and updates look the same, and deletes carry their identity in an unsigned header.

**Why It Happens:** Medplum posts the resource without an interaction field, and delete notifications have an empty body.

**Workarounds:**

* Use `subscription-supported-interaction` to split creates, updates and deletes into separate Subscriptions and endpoints.
* Confirm deletions through the API.

**How Hookdeck Can Help:** Hookdeck can route by path or header to different destinations, and filters can match on `X-Medplum-Deleted-Resource` to send deletions to their own handler.

### Bot subscriptions don't retry

**The Problem:** Failures in Bot-backed Subscriptions are never retried.

**Why It Happens:** `subscription-max-attempts` applies only to rest-hook Subscriptions with external HTTP endpoints. Bots run once.

**Workarounds:**

* Build retry logic into the Bot, or have it hand work to an external endpoint.
* Watch Bot `AuditEvent` records for failures.

**How Hookdeck Can Help:** For work that needs retries, point a rest-hook Subscription at Hookdeck and let it retry your service.

## Best practices

### Hash the raw body

Medplum's TypeScript example re-serialises parsed JSON. Use the bytes you received, as the Python example does.

### Size retries to your downtime

Choose `subscription-max-attempts` from Medplum's table based on the longest outage you plan for, not the default.

### Make writes version-aware

Use `meta.versionId` or `meta.lastUpdated` to ignore duplicates and older versions. The [webhook idempotency guide](/webhooks/guides/implement-webhook-idempotency) covers the general approach.

### Keep clinical data out of the request path

Store the resource, respond, and process it elsewhere, following [asynchronous webhook processing](/webhooks/guides/why-implement-asynchronous-processing-webhooks). Keep PHI out of logs.

## Conclusion

Medplum webhooks are FHIR rest-hook Subscriptions configured with Medplum extensions. Turn on signing with `subscription-secret`, verify `X-Signature` against the raw body, treat empty bodies as deletions to confirm, and raise `subscription-max-attempts` well above the default if your endpoint can ever be down for more than a couple of minutes.

[Hookdeck Event Gateway](https://hookdeck.com) adds durable storage and long-running retries in front of your FHIR integrations.

[Get started with Hookdeck](https://dashboard.hookdeck.com/signup) for free and handle Medplum webhooks reliably in minutes.