On this page

FHIR Batch Requests

FHIR allows users to create batch requests to bundle multiple API calls into a single HTTP request. Batch requests can improve speed and efficiency and can reduce HTTP traffic when working with many resources.

Cloning a project

If you want to create a copy of a project, say for a new environment, this can be done using the $clone operation rather than by creating a batch request. For more details see the Projects guide.

Batches vs Transactions​

Use a batch Bundle for operations that can succeed independently. Some entries may succeed while others fail. For imports and synchronization, prefer conditional upserts keyed by stable identifiers, inspect every response entry, and retry failed operations when appropriate.

FHIR also defines transaction for an all-or-nothing commit: every operation succeeds or the entire group rolls back. Use atomicity only when a partially committed group would violate a business rule, even temporarily. Resources referring to one another does not, by itself, establish that requirement. See References in Bundles for dependency handling.

Atomic transaction Bundles are unavailable on hosted Medplum

The transaction-bundles feature is currently unavailable on Medplum-hosted deployments.

Without this feature, a Bundle with type: "transaction" is processed with batch semantics. Entries can fail independently, successful writes are not rolled back, and the server returns no warning about the loss of atomicity. The response can still be labeled transaction-response; that label does not prove atomic processing occurred.

Use type: "batch" when partial success is acceptable. If your workflow requires an all-or-nothing commit, a batch with retries does not satisfy that requirement. Revisit the workflow before relying on it in a hosted deployment.

Choosing a write pattern​

RequirementPattern
Import or synchronize independent recordsBatch conditional upserts; inspect each result and handle failures individually
Link new resourcesWrite dependencies first, confirm success, then write dependents using the saved references
Prevent another writer's changes from being overwrittenVersion checking with ifMatch, including on individual batch entries
Book or hold an appointment across schedulesUse the scheduling operations, which validate availability and manage their own database transactions
Commit several resource changes together with no partially committed stateRequires atomic transaction support; currently unavailable for general Bundle submissions on hosted Medplum

Atomicity does not replace idempotency, conflict handling, or response inspection. It also does not make downstream subscriptions, external services, or separate client reads observe all changes simultaneously.

Transaction Limits​

For deployments that enable atomic transactions, configuration and limits are documented in the administrator reference. These settings do not change hosted availability.

How to Perform a Batch Request​

Batch requests are performed by sending a POST request to [baseURL]/ with a FHIR Bundle. The Medplum SDK provides the executeBatch helper function to simplify this operation.

The details of your request will be in the entry field of the Bundle, which is an array of BundleEntry objects. Each BundleEntry should have the details of the resource you are working with, as well as additional information about the request you are making.

ElementDescription
request.urlThe URL to send your request to. This is relative to the base R4 FHIR URL (e.g. https://api.medplum.com/fhir/R4).
request.methodThe type of HTTP request: GET (read a resource or perform a search), POST (create), PUT (update), DELETE (delete).
request.ifNoneExistSee below
resourceThe details of the FHIR resource that is being created/updated.
fullUrlSee below
Example: A simple batch request to simultaneously search for two patients
await medplum.executeBatch({
  resourceType: 'Bundle',
  type: 'batch',
  entry: [
    {
      request: {
        method: 'GET',
        url: 'Patient/homer-simpson',
      },
    },
    {
      request: {
        method: 'GET',
        url: 'Patient/marge-simpson',
      },
    },
  ],
});
medplum post Bundle '
  {
    "resourceType": "Bundle",
    "type": "batch",
    "entry": [
      {
        "request": {
          "method": "GET",
          "url": "Patient/homer-simpson",
        },
      },
      {
        "request": {
          "method": "GET",
          "url": "Patient/marge-simpson",
        },
      },
    ],
  }'
curl 'https://api.medplum.com/fhir/R4' \
  -X POST
  -H 'authorization: Bearer $ACCESS_TOKEN' \
  -H 'content-type: application/fhir+json' \
  -d '{
    "resourceType": "Bundle",
    "type": "batch",
    "entry": [
      {
        "request": {
          "method": "GET",
          "url": "Patient/homer-simpson",
        },
      },
      {
        "request": {
          "method": "GET",
          "url": "Patient/marge-simpson",
        },
      },
    ],
  }'
Example: Create multiple resources in one batch request
{
  resourceType: 'Bundle',
  type: 'batch',
  entry: [
    {
      resource: {
        resourceType: 'Patient',
        identifier: [
          {
            system: 'https://example-org.com/patient-ids',
            value: 'homer-simpson',
          },
        ],
        name: [
          {
            family: 'Simpson',
            given: ['Homer', 'Jay'],
          },
        ],
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
    {
      resource: {
        resourceType: 'Patient',
        identifier: [
          {
            system: 'https://example-org.com/patient-ids',
            value: 'marge-simpson',
          },
        ],
        name: [
          {
            family: 'Simpson',
            given: ['Marge', 'Jacqueline'],
          },
        ],
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
  ],
};
Example: Make multiple calls to the _history endpoint in one batch request
{
  resourceType: 'Bundle',
  type: 'batch',
  entry: [
    {
      request: {
        method: 'GET',
        url: 'Patient/homer-simpson/_history',
      },
    },
    {
      request: {
        method: 'GET',
        url: 'Patient/marge-simpson/_history',
      },
    },
    {
      request: {
        method: 'GET',
        url: 'Organization/_history',
      },
    },
  ],
};

Asynchronous Batch Requests​

Synchronous batch requests are subject to an 8 MB request size limit (Medplum-hosted) and a 60 second timeout. If your use case exceeds these constraints, Medplum offers asynchronous batch requests. There are two main reasons you may want to process a batch asynchronously:

  1. Large or slow bundles — Bundles that exceed the 8 MB size limit or take more than 15 seconds to process may fail mid-request due to the request timeout. Async processing raises the size limit to 50 MB and removes the timeout by enqueuing the bundle for background processing.
  2. FHIR quota avoidance — Asynchronous batch requests do not count against a user's FHIR interaction quota. This makes async the preferred approach for large data seeding or import jobs where quota limits would otherwise be a concern.

In both cases, the Bundle is enqueued on the server and a response is sent back to the client immediately with a URL where it can receive status updates around the batch processing job. Successful entries are written as the job runs; no additional step is required to apply those writes. Job completion does not mean every entry succeeded.

Data availability

Because async batches are processed in the background, data is not immediately available after the request returns. Poll the AsyncJob status URL, then inspect every entry in the result Bundle and resolve failures before treating the import as complete. This makes async batches best suited for scheduled or pre-planned jobs rather than last-minute operations where changes are needed immediately.

When to use async vs. sync​

ScenarioRecommendation
Bundle is small and inexpensiveSync (default)
Bundle is large (approaching 5 MB+) or risks timeoutAsync
Seeding demo or test data ahead of timeAsync (avoids quota, schedule in advance)
Data must be available immediatelySync (ensure quota headroom or raise userFhirQuota)
High-volume import where quota is the bottleneckAsync

For a full, step-by-step guide detailing how to submit and poll for the results of asynchronous operations, see Processing asynchronous bundles.

To opt into asynchronous handling of the batch request, add the Prefer: respond-async header to the HTTP request for the batch:

curl 'https://api.medplum.com/fhir/R4' \
  -X POST
  -H 'authorization: Bearer $ACCESS_TOKEN' \
  -H 'content-type: application/fhir+json' \
  -H 'prefer: respond-async'
  -d @large-bundle.json

See the FHIR Asynchronous Request pattern for more information.

Response Structure​

When you submit a batch request, the server returns a Bundle with type set to batch-response. A request labeled transaction produces a transaction-response label even when the feature is disabled. Always apply the availability and atomicity rules, rather than inferring guarantees from the response label.

The response Bundle contains an entry array that corresponds one-to-one with the entries in the request Bundle. The order of entries in the response matches the order in the request.

Each entry in the response Bundle contains a response element with the following fields:

FieldDescription
statusThe HTTP status code for the operation (e.g., "200", "201", "404").
outcomeAn OperationOutcome resource containing details about the operation result.
locationFor successful create operations, the location of the created resource.

If the operation returned a resource (e.g., a read or search operation, or a create operation returning the created resource), it will be included in the resource field of the entry.

Error Handling​

Error handling depends on whether atomic transaction processing is enabled, as well as the requested Bundle type. On hosted Medplum, handle partial failures for both request types.

Batch Requests (type: batch)

In a batch request, operations are independent. If one operation fails, it does not stop the processing of other operations (unless a system limit like a Rate Limit is reached).

  • Success: The entry will have a 2xx status code.
  • Failure: The entry will have a 4xx or 5xx status code. The response.outcome will contain an OperationOutcome describing the error.

Example of a batch response with one success and one failure:

{
  "resourceType": "Bundle",
  "type": "batch-response",
  "entry": [
    {
      "response": {
        "status": "201",
        "location": "Patient/123"
      },
      "resource": {
        "resourceType": "Patient",
        "id": "123"
        // ...
      }
    },
    {
      "response": {
        "status": "404",
        "outcome": {
          "resourceType": "OperationOutcome",
          "issue": [
            {
              "severity": "error",
              "code": "not-found",
              "diagnostics": "Not found"
            }
          ]
        }
      }
    }
  ]
}

Transaction Requests (type: transaction)

The following behavior applies only when atomic transaction support is enabled. It is currently unavailable on hosted Medplum. If any operation fails, the entire transaction is rolled back, and the server returns an error for the whole request.

  • Success: All operations succeeded. The response Bundle contains results for all entries.
  • Failure: The server returns an OperationOutcome describing the error that caused the transaction to fail. No partial results are returned.

References in Bundles​

When using batch requests, it is common to require resources to refer to one another: either between two resources within the Bundle, or to resources outside the Bundle. FHIR provides ways to automatically link the resources together, without needing to know the exact resource IDs up front.

Internal References​

Resources within the same Bundle often need to link to one another, such as an Encounter referring to a new Patient. On hosted Medplum, prefer writing the Patient first, confirming success, and then writing the Encounter with the saved Patient reference. This separates dependency ordering from atomicity.

Creating internal references is done by assigning temporary IDs to each bundle entry. The fullUrl field is set to 'urn:uuid:' followed by a temporary UUID.

Other Bundle entries can refer to this resource using the temporary urn:uuid: string. Medplum replaces these placeholders with real references in both batch and transaction Bundles. The transaction example below can partially succeed on hosted Medplum; inspect every response entry before using the created resources.

reorderBundle() from @medplum/core can help put prerequisites before dependents. The server also groups entries by interaction type; resolving a reference does not confirm that its target was saved. Ordering does not provide rollback or prevent a dependent write after a prerequisite fails.

Example: Create a patient and encounter whose subject is the created patient
{
  resourceType: 'Bundle',
  type: 'transaction',
  entry: [
    {
      fullUrl: 'urn:uuid:f7c8d72c-e02a-4baf-ba04-038c9f753a1c',
      resource: {
        resourceType: 'Patient',
        name: [
          {
            prefix: ['Ms.'],
            family: 'Doe',
            given: ['Jane'],
          },
        ],
        gender: 'female',
        birthDate: '1970-01-01',
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
    {
      fullUrl: 'urn:uuid:7c988bc7-f811-4931-a166-7c1ac5b41a38',
      resource: {
        resourceType: 'Encounter',
        status: 'finished',
        class: { code: 'ambulatory' },
        subject: {
          reference: 'urn:uuid:f7c8d72c-e02a-4baf-ba04-038c9f753a1c',
          display: 'Ms. Jane Doe',
        },
        type: [
          {
            coding: [
              {
                system: 'http://snomed.info/sct',
                code: '162673000',
                display: 'General examination of patient (procedure)',
              },
            ],
          },
        ],
      },
      request: {
        method: 'POST',
        url: 'Encounter',
      },
    },
  ],
};

External (Conditional) References​

Additionally, it may be necessary to link to resources that already exist on the server outside of the Bundle, for which the ID of the target resource is not known. To handle this use case, FHIR allows populating the reference with a search query string, which will be resolved by Medplum server at resource creation time. This search must resolve to a single resource, otherwise an error will be returned. For example:

Example: Create multiple patients that link to the same provider
{
  resourceType: 'Bundle',
  type: 'batch',
  entry: [
    {
      resource: {
        resourceType: 'Patient',
        name: [
          {
            prefix: ['Ms.'],
            family: 'Doe',
            given: ['Jane'],
          },
        ],
        gender: 'female',
        birthDate: '1970-01-01',
        generalPractitioner: [{ reference: 'Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|1234567893' }],
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
    {
      resource: {
        resourceType: 'Patient',
        name: [
          {
            prefix: ['Mr.'],
            family: 'Doe',
            given: ['John'],
          },
        ],
        gender: 'male',
        birthDate: '1972-12-31',
        generalPractitioner: [{ reference: 'Practitioner?identifier=http://hl7.org/fhir/sid/us-npi|1234567893' }],
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
  ],
};

Conditional Batch Actions​

There may be situations where you would only like to create a a resource as part of a batch request if it does not already exist.

You can conditionally perform batch actions by adding the ifNoneExist property to the request element of your Bundle.

Conditional creates do not require atomic transaction support. The linked-resource example below can partially succeed on hosted Medplum. Prefer saving the Organization first and then writing the Patient with its returned reference when you need to recover the steps independently.

The ifNoneExist property uses search parameters to search existing resources and only performs the action if no match is found. Since you are already defining the url to send the request to, you only need to enter the actual parameter in this field (i.e., everything that would come after the ? when submitting an actual search).

Example: Create a patient and organization, only if the organization does not already exist
{
  resourceType: 'Bundle',
  type: 'transaction',
  entry: [
    {
      fullUrl: 'urn:uuid:4aac5fb6-c2ff-4851-b3cf-d66d63a82a17',
      resource: {
        resourceType: 'Organization',
        identifier: [
          {
            system: 'http://example-org.com/organizations',
            value: 'example-organization',
          },
        ],
        name: 'Example Organization',
      },
      request: {
        method: 'POST',
        url: 'Organization',
        ifNoneExist: 'identifier=http://example-org.com/organizations|example-organization',
      },
    },
    {
      fullUrl: 'urn:uuid:37b0dfaa-f320-444f-b658-01a04985b2ce',
      resource: {
        resourceType: 'Patient',
        name: [
          {
            use: 'official',
            family: 'Smith',
            given: ['Alice'],
          },
        ],
        gender: 'female',
        birthDate: '1974-12-15',
        managingOrganization: {
          reference: 'urn:uuid:4aac5fb6-c2ff-4851-b3cf-d66d63a82a17',
          display: 'Example Organization',
        },
      },
      request: {
        method: 'POST',
        url: 'Patient',
      },
    },
  ],
};

Preventing Lost Updates with Version Checking​

Use the ifMatch property on individual batch entry requests to prevent lost updates. Each update succeeds only if the resource has not changed since the version you read. This protection does not require the transaction-bundles feature.

Example: Version Checking in a Batch
// Read the current version of resources you want to update
const patient1 = await medplum.readResource('Patient', 'patient-1');
const patient2 = await medplum.readResource('Patient', 'patient-2');

// Create a batch with independent version checks
// Note: Bundle entry ifMatch uses ETag format W/"versionId" because it becomes an HTTP header
const versionCheckedBatch: Bundle = {
  resourceType: 'Bundle',
  type: 'batch',
  entry: [
    {
      request: {
        method: 'PUT',
        url: 'Patient/patient-1',
        // Bundle entries use ETag format: W/"versionId"
        // This is the same format as the If-Match HTTP header.
        ifMatch: patient1.meta?.versionId ? `W/"${patient1.meta.versionId}"` : undefined,
      },
      resource: {
        ...patient1,
        name: [{ family: 'Smith', given: ['John'] }],
      },
    },
    {
      request: {
        method: 'PUT',
        url: 'Patient/patient-2',
        ifMatch: patient2.meta?.versionId ? `W/"${patient2.meta.versionId}"` : undefined,
      },
      resource: {
        ...patient2,
        active: false,
      },
    },
  ],
};

const versionCheckedResults = await medplum.executeBatch(versionCheckedBatch);
for (const entry of versionCheckedResults.entry ?? []) {
  console.log(entry.response?.status, entry.response?.outcome);
}
// Inspect every entry. A 412 affects only that entry; reload and review it before retrying.

If a resource version no longer matches, that entry returns 412 Precondition Failed; other batch entries can still succeed. Inspect each response, reload conflicting resources, and review the intended changes before trying again. Do not replay stale resource bodies automatically.

ifMatch works the same way on DELETE entries, so a delete only succeeds if the resource is still at the version you read.

Performing Upserts​

An upsert creates or updates one resource through a conditional update. Group independent upserts in a batch to reduce HTTP requests. Match on a stable identifier and include that identifier in the resource body. Each upsert is a separate operation; the batch has no all-or-nothing guarantee.

const sourcePatients: Patient[] = [
  {
    resourceType: 'Patient',
    identifier: [{ system: 'https://example.org/source-patients', value: 'P001' }],
    name: [{ family: 'Doe', given: ['Jane'] }],
  },
  {
    resourceType: 'Patient',
    identifier: [{ system: 'https://example.org/source-patients', value: 'P002' }],
    name: [{ family: 'Smith', given: ['Alex'] }],
  },
];
const upsertEntries: BundleEntry[] = sourcePatients.map((resource) => {
  const identifier = resource.identifier?.[0];
  if (!identifier?.system || !identifier.value) {
    throw new Error('Source patient must have a stable identifier');
  }
  return {
    resource,
    request: {
      method: 'PUT',
      url: `Patient?identifier=${encodeURIComponent(`${identifier.system}|${identifier.value}`)}`,
    },
  };
});
// A request-level failure can throw before returning a result Bundle.
// Handle it separately; reconcile unknown outcomes (such as timeouts) before retrying.
// The loop below handles per-entry results only.
const upsertResults = await medplum.executeBatch({
  resourceType: 'Bundle',
  type: 'batch',
  entry: upsertEntries,
});
const retryEntries: BundleEntry[] = [];
const reviewEntries: { request: BundleEntry; response: BundleEntry | undefined }[] = [];
for (const [index, request] of upsertEntries.entries()) {
  const response = upsertResults.entry?.[index];
  const status = Number.parseInt(response?.response?.status ?? '', 10);
  if (status >= 200 && status < 300) {
    continue; // Record success; do not resubmit this entry.
  }
  if (status === 429 || (status >= 500 && status < 600)) {
    retryEntries.push(request); // Retry with a bounded backoff policy.
  } else {
    reviewEntries.push({ request, response }); // Includes missing/unknown results.
  }
}
// Persist results, schedule bounded retries, and surface reviewEntries to the operator.

Persist the submitted entries and their results. Retry the selected transient failures with bounded exponential backoff, honoring Retry-After when available. Correct validation or authorization failures before retrying; reload and review version conflicts. A missing response is an unknown outcome that needs reconciliation, not proof of failure.

This example assumes independent records and that the source still owns the fields being replaced. Upserts avoid duplicate resource identities; they can still overwrite newer edits or retrigger automation. If a request times out before returning results, reconcile outcomes before retrying. For linked resources, confirm prerequisite writes and replace temporary references with saved IDs before retrying dependent entries.

Upsert URLs

Because resolving the search request in the upsert URL is a prerequisite to determine which ID should be assigned as part of handling internal references, the urn:uuid: syntax for internal references cannot be used in the Bundle.entry.request.url for a conditional update within a batch.

Instead, upsert URLs should link to other resources within the Bundle consistently through conditions on the target resource itself, not its server-assigned ID.

The examples below illustrate URL construction. For dependency ordering and partial-failure handling, see Internal References.

Example

❌ Incorrect

{
  "resourceType": "Bundle",
  "type": "batch",
  "entry": [
    {
      "fullUrl": "urn:uuid:4410cb87-4a38-4d3f-bee8-3c3556e6debc",
      "request": {
        "method": "PUT",
        "url": "Patient?identifier=http://example.com/mrn|1234567"
      },
      "resource": {
        "resourceType": "Patient",
        "identifier": [{ "system": "http://example.com/mrn", "value": "1234567" }]
      }
    },
    {
      "fullUrl": "urn:uuid:b122a53c-9c0d-4654-9260-c0b67b7bc5d4",
      "request": {
        "method": "PUT",
        // Incorrect: Upsert URL cannot use replaced urn:uuid: syntax
        "url": "CareTeam?subject=urn:uuid:4410cb87-4a38-4d3f-bee8-3c3556e6debc"
      },
      "resource": {
        "resourceType": "CareTeam",
        "subject": { "reference": "urn:uuid:4410cb87-4a38-4d3f-bee8-3c3556e6debc" }
      }
    }
  ]
}

✅ Correct

{
  "resourceType": "Bundle",
  "type": "batch",
  "entry": [
    {
      "fullUrl": "urn:uuid:4410cb87-4a38-4d3f-bee8-3c3556e6debc",
      "request": {
        "method": "PUT",
        "url": "Patient?identifier=http://example.com/mrn|1234567"
      },
      "resource": {
        "resourceType": "Patient",
        "identifier": [{ "system": "http://example.com/mrn", "value": "1234567" }]
      }
    },
    {
      "fullUrl": "urn:uuid:b122a53c-9c0d-4654-9260-c0b67b7bc5d4",
      "request": {
        "method": "PUT",
        // Correct: Refer to subject via chained search,
        // using same identifier as its own upsert URL
        "url": "CareTeam?subject.identifier=http://example.com/mrn|1234567"
      },
      "resource": {
        "resourceType": "CareTeam",
        "subject": { "reference": "urn:uuid:4410cb87-4a38-4d3f-bee8-3c3556e6debc" }
      }
    }
  ]
}

PATCH actions in a Batch​

Because the request body of a PATCH request is an array of JSON Patch operations, not a resource, some extra conversion is required to represent these actions in a batch request. The FHIR recommended pattern for this use case is to base64 encode the JSON Patch array and represent it as a Binary resource:

{
  "request": {
    "method": "PATCH",
    "url": "Patient/6ffaaab4-ff7e-4416-80c7-8fce95c3e31c"
  },
  "resource": {
    "resourceType": "Binary",
    "contentType": "application/json-patch+json",
    // Encoded: [{"op":"test","path":"/active","value":false}]
    "data": "W3sib3AiOiJyZXBsYWNlIiwicGF0aCI6Ii9hY3RpdmUiLCJ2YWx1ZSI6ZmFsc2V9XQo="
  },
}

Additionally, Medplum supports passing JSON Patch formatted as a Parameters resource, making it easier to see what operations are happening in the batch.

Value Formatting

To avoid parsing ambiguity and simplify the format of the Parameters, all values are passed as JSON strings, via the valueString field on each corresponding Parameter.parameter.part with "name": "value".

All types of values, including booleans, strings, objects, and arrays, should be passed to JSON.stringify() or equivalent rather than being included directly in the Parameters.

{
  "request": {
    "method": "PATCH",
    "url": "Patient/6ffaaab4-ff7e-4416-80c7-8fce95c3e31c"
  },
  "resource": {
    "resourceType": "Parameters",
    "parameter": [
      {
        "name": "operation",
        "part": [
          { "name": "op", "valueCode": "test" },
          { "name": "path", "valueString": "/active" },
          { "name": "value", "valueString": "false" }
        ]
      },
      {
        "name": "operation",
        "part": [
          { "name": "op", "valueCode": "add" },
          { "name": "path", "valueString": "/name/-" },
          // Note that values must be JSON encoded
          { "name": "value", "valueString": "{\"given\":[\"Dave\"],\"family\":\"Smith\"}" }
        ]
      }
    ]
  }
}

Medplum Autobatching​

The Medplum Client provides the option to automatically batch FHIR read and search requests using the autoBatchTime parameter. This field allows you to set a time window during which to batch up any GET requests. After this window expires, the MedplumClient will add them to a Bundle behind the scenes and then execute them as a batch request.

Autobatching works by creating a queue of Promises issued within the autoBatchTime window and then creating a bundle out of these requests. To allow the queue to be created, you must make sure that the main thread continues to run, so you should not use await after each request. Using await will pause the main thread each time a request is made, so a queue cannot be created.

Instead you should create the queue of Promise requests and then use Promise.all() to resolve all of them at once.

Resolving Promises with autobatching

❌ WRONG

// Main thread pauses and waits for Promise to resolve. This request cannot be added to a batch
await medplum.createResource({
  resourceType: 'Patient',
  name: [
    {
      family: 'Smith',
      given: ['John'],
    },
  ],
});

// Main thread pauses and waits for Promise to resolve. This request cannot be added to a batch
await medplum.createResource({
  resourceType: 'Patient',
  name: [
    {
      family: 'Simpson',
      given: ['Homer', 'Jay'],
    },
  ],
});

✅ CORRECT

const patientsToCreate = [];

// Main thread continues
patientsToCreate.push(
  medplum.createResource({
    resourceType: 'Patient',
    name: [
      {
        family: 'Smith',
        given: ['John'],
      },
    ],
  })
);

// Main thread continues
patientsToCreate.push(
  medplum.createResource({
    resourceType: 'Patient',
    name: [
      {
        family: 'Simpson',
        given: ['Homer', 'Jay'],
      },
    ],
  })
);

// Both promises are resolved simultaneously
await Promise.all(patientsToCreate);