On this page

Running Server Side Code: Bots and Subscriptions

Should your code run when FHIR data changes, when an application calls it, when an external service sends an event, or on a schedule? This guide helps you choose what starts the code (its trigger) and where the code runs.

  • A Bot runs your custom JavaScript or TypeScript function in Medplum. That function is called the handler.
  • A Subscription defines which FHIR resource changes send a notification to your code. It can invoke a Bot or send an HTTP request to your service's HTTPS URL, called an endpoint.

For example, a Subscription can detect a newly created Patient and invoke a Bot that registers that patient in another system. The Subscription selects the change; the Bot performs the action. The FHIR event notifications covered here are sent after a resource change is saved.

We recommend Medplum Bots for handling FHIR event notifications. The Bot framework provides a Medplum client, configurable permissions, project secrets, and execution logging. On hosted Medplum, it also manages the execution infrastructure.

  1. Choose what starts the work. Select a trigger for each use case.
  2. For a Subscription, choose its destination. Start with a Bot; consider your own endpoint for specific service or runtime requirements.
  3. For a Subscription, choose its matching changes. Select creation, updates, a specific state transition, or deletion based on its purpose.
Plan with this guide

Copy this prompt into your AI agent. It will use this guide and your existing project context, ask about missing requirements, and save decisions for later development. See setup and examples.

Help me plan this part of my Medplum application using this guide:
Running Server Side Code: Bots and Subscriptions
https://www.medplum.com/docs/decision-guides/running-server-side-code
Local source, if cloned: medplum-link/packages/docs/content/docs/decision-guides/running-server-side-code.md

Follow medplum-link/packages/docs/static/ai/planning.md
(or https://www.medplum.com/ai/planning.md), including its Medplum rules.
Ask before creating or changing my app's project instruction files.

Read my existing requirements and decisions, then ask me about consequential missing requirements; do not invent answers. Save and summarize the decisions in my app's repo before implementation.

Decision 1: What should start the work?​

Choose the trigger separately for each use case, according to the source of work. The code can run in a Medplum Bot or your own service. A handler can support multiple triggers when it accepts each input format and runs with appropriate permissions. If two triggers can start the same action, ensure they do not perform it twice.

Option A: FHIR resource change → Subscription​

Use a Subscription when the same action should follow a matching resource change regardless of which application screen, integration, or background process made the change. The Subscription can invoke a Bot or send an HTTPS notification to your service.

  • Example: Start a registration integration when a Patient is created.
  • Best fit: The saved resource change is what should start the action.
  • Tradeoff: The notification happens after the write is committed. A handler failure leaves that write saved, and the application tracks whether the resulting action completed.

Continue to Decisions 2 and 3 to choose the destination and matching changes. For a result or validation response returned to the caller, consider direct invocation below.

Option B: Application request → direct invocation​

Have the application call server side code when it explicitly requests a calculation or action. For a Bot, use its $execute endpoint or expose it as a custom FHIR operation. For your own service, call its API.

  • Example: Calculate a score when a user requests it in the application.
  • Best fit: The application chooses when to run the code and supplies its input. When it waits for the response, the handler can return a result or validation error.
  • Tradeoff: The application owns the call and handles its response or failure. The handler must fit its runtime's execution limits.

If the handler validates an action, call it before saving that action and ensure callers use that path. Ordinary FHIR writes only use this validation when callers explicitly invoke it.

Bot implementation: Bot $execute, Custom FHIR Operations.

Option C: Recurring time → schedule​

Use a Bot's cron configuration or your service's scheduler to run code at a recurring time.

  • Example: Reconcile records with another system each night.
  • Best fit: Periodic checks or work that should run at a regular interval.
  • Tradeoff: Work waits until the next scheduled run. The handler must select the records to act on and handle repeated or overlapping runs safely.

Bot implementation: Cron Jobs for Bots.

Option D: External service event → incoming webhook​

An external provider sends an HTTP request, called a webhook, to a Bot or an HTTPS endpoint in your service when an event occurs in the provider's system.

  • Example: Update a communication record when a messaging provider reports delivery.
  • Best fit: The event originates outside Medplum and the service supports webhook delivery.
  • Tradeoff: The handler must verify the sender, validate its payload, and handle the provider's repeated deliveries safely.

Bot implementation: Consuming Webhooks.

Next: If you chose Option A, continue to Decisions 2 and 3. For other triggers, use the linked Bot docs or configure your own service, then follow the production checks at the end of this guide.

Decision 2: Where should this Subscription send notifications?​

Complete this decision if you chose Option A: FHIR resource change in Decision 1.

For each Subscription, start with a Medplum Bot. Use your own endpoint when a specific service or runtime requirement justifies operating the receiver yourself.

  • Advantages:
    • Managed hosting: On hosted Medplum, deploy your handler without operating an HTTPS receiver or a separate application server.
    • Ready-to-use client: The handler receives a Medplum client that reads and writes FHIR resources with the Bot's configured permissions.
    • Integrated access and secrets: Use an AccessPolicy to limit what the Bot can access and project secrets for external API credentials.
    • Built-in execution logging: Use Bot execution records (AuditEvents) and captured console output to investigate runs and failures.
    • Development tooling: Use Medplum's Bot testing tools and CLI deployment workflow alongside your application's source control and CI.
  • Tradeoffs:
    • Code and dependencies must be supported by the Bot runtime and fit its memory and execution time limits.
    • Your team owns the handler's logic, tests, and recovery when an action fails.
  • Best fit: The recommended starting point for handlers that read or write Medplum resources or call another API.

Implementation: Configure a Bot destination, Bots in Production.

Option B: Your own HTTPS endpoint for specific requirements​

Use this path when an existing service must handle the action or a required language, dependency, or execution environment is outside the Bot runtime. Your team takes responsibility for the receiver and its Medplum integration.

  • Advantages:
    • Keeps the action in an existing service when that service needs to own it.
    • Accommodates runtime requirements the Bot environment cannot meet.
  • Tradeoffs:
    • Your team hosts, secures, deploys, and maintains the availability of the HTTPS receiver.
    • You verify notification signatures and manage separate API credentials if the service reads or writes Medplum resources.
    • You connect delivery records to your service's logs and monitor both delivery and handler failures.
    • If the receiver queues an action, your service tracks completion and handles worker retries after acknowledging the notification.
  • Best fit: A concrete requirement for an existing service or a different runtime outweighs the additional integration and operational work.

Implementation: Configure an HTTPS destination.

Next for either option: For each Subscription, choose which resource changes should start its handler.

Decision 3: Which changes should trigger this Subscription?​

Complete this decision if you chose Option A: FHIR resource change in Decision 1.

Choose this separately for each Subscription, based on its handler's purpose. An application can use different Subscriptions for Patient creation, demographic updates, and QuestionnaireResponse completion. A state transition is an additional filter on creation or updates. Combine the options as needed.

Option A: Resource creation​

Notify the handler when a new resource is saved.

  • Example: Start a registration integration when a Patient is created.
  • Configuration: Use criteria to select resources and a create interaction extension to select creation events.

Option B: Resource updates​

Notify the handler when an existing resource changes.

  • Example: Synchronize Patient demographics with another system.
  • Configuration: Resource criteria and an update interaction extension. Filter relevant field changes when the handler should run only for those changes.

Option C: A specific state transition​

Notify the handler when a resource enters the state that should start the action.

  • Example: Handle a QuestionnaireResponse when it becomes completed.
  • Configuration: Resource criteria, selected create/update interactions, and a transition expression. A filter for a completed status alone also matches later edits while that status remains completed.
  • Decide explicitly: Should creation in the target state also send a notification?

Option D: Resource deletion​

Notify the handler when a matching resource is deleted.

  • Example: Remove a downstream copy of the resource.
  • Configuration: A delete interaction extension and a handler that supports the destination's deletion payload.

Implementation: Select the resource change, Subscription Extensions.

Before enabling in production​

  • Set permissions. Give the Bot or service access to the resources its handler needs. For Subscriptions, also verify account scope.
  • Handle repeated execution safely. Repeated delivery, a repeated request, or a manual rerun should preserve the intended result without duplicating an action.
  • Monitor failures and define recovery. Use Bot monitoring and recovery or your service's monitoring to find failed actions. For Subscriptions, external HTTP delivery has configurable retries; those retry settings do not automatically rerun failed Bot logic.
  • Test the configured trigger. Verify its inputs, execution identity, intended effects, and failure behavior in a test project before enabling it in production.

Continue with Bots in Production for deployment and configuration, or Implementing FHIR Event Notifications for Subscription setup and verification.