Google BigQuery adapter
Stream or upsert workflow output into BigQuery tables and run queries against them from a workflow.
On this page
The Google BigQuery adapter (bigquery) streams rows from a workflow into an existing BigQuery table or upserts them by key, runs parameterized GoogleSQL queries and passes the rows to the next step, and reads new rows on a schedule as the reader of a polling trigger. It is for healthcare organizations that keep their warehouse in BigQuery, next to a MedHook engine on GKE. On GKE the engine signs in with its own Google identity, so no key is stored.
flowchart LR
SRC["HL7v2, FHIR or CSV\nsource"] --> ENG["MedHook engine\non GKE"]
ENG == "insert\n(insert-only role on the dataset)" ==> BQ[("BigQuery\ndataset")]
ENG == "upsert by key\n(MERGE: dataEditor + jobUser)" ==> BQ
BQ -- "query or poll\n(dataViewer + jobUser)" --> ENG
TEAM["Your analysts\nand reports"] -- "Google IAM" --> BQHow it works
- Sign-in. On GKE the token comes from the metadata server for the engine's Google service account (Workload Identity). There is no key to store or rotate. An engine outside GKE can use a stored service account key instead. The token is cached and fetched again once after a 401.
- Requests. The adapter calls the BigQuery REST API on
bigquery.googleapis.com. Every request stays under the profile's/projects/paths; a redirect anywhere else is refused, not followed. With Workload Identity a profile CA (tlsCaPem) is refused, because the requests carry the engine's own Google token; they are verified against the system CAs. The project, dataset and table come from the profile and the step, never from a message. - Insert. Rows are streamed into an existing table (
tabledata.insertAll), at most 10,000 rows and 9.5 MB per step. The adapter creates no tables and does not split a batch. - Upsert by key. One MERGE per step on the key columns you name, with every row sent as a query parameter. A new key inserts a row and a key already in the table updates it, so a retry, a resend or a replay never adds a second row. The rows are checked against the table's columns first.
- Query and poll. One GoogleSQL statement, with values sent as query parameters. Every job carries a bytes-billed limit, so a query that would scan more than you allow fails without running.
- Retries. A rate limit, a 5xx or a timeout is retried with the step's retry settings, and a 429's
Retry-Afteris respected. A refused request (access denied, not found, invalid SQL, a daily quota) fails the step without a retry. An insert that timed out or got a 5xx after it was sent is marked uncertain and is not retried, because BigQuery may have stored the rows. An outbound proxy refusing the tunnel is retried like a refused connection; a TLS certificate failure or a proxy 407 fails without a retry. A query or poll the engine stops waiting for (queryTimeoutMs, or the run is cancelled) also cancels its BigQuery job.
Turn it on
1. Create the table
Create the dataset and table in BigQuery yourself, with the columns your workflow writes. MedHook never creates or deletes datasets or tables. Enable the BigQuery API (bigquery.googleapis.com) in the project that holds the dataset, and in the job project if you use a separate one.
2. Grant access
With the engine's Terraform module (Install), list the datasets in terraform.tfvars and apply:
engine_bigquery_datasets = [
{ dataset = "clinical_rows" }, # insert-only custom role
{ project = "demohealth-analytics", dataset = "reporting", access = "read" }, # roles/bigquery.dataViewer
]
# Only if workflows run query or poll steps:
engine_bigquery_job_project = "demohealth-prod"Terraform grants the engine's Google service account a role on each dataset, and roles/bigquery.jobUser on the job project. It grants nothing else. access = "write" (the default) is an insert-only custom role that cannot read rows or change tables, "read" is roles/bigquery.dataViewer, and "edit" is roles/bigquery.dataEditor for a dataset the engine both reads and writes; it can also delete tables. Without the module, grant the same roles yourself; see Access.
3. Create the profile
Choose New connection on the Adapters page, pick BigQuery and set project and dataset. Leave authType at workload-identity on GKE. Set location to the dataset's location, such as EU or europe-west2, whenever it is not US, and jobProject when jobs run in another project. Every setting is in Adapter settings.
4. Test it
Test connection reads the dataset. It fails with the reason, such as accessDenied or notFound, and never shows table data.
5. Add an insert or upsert step
In the builder, add a Data Map that shapes each message into the table's columns, then a destination step with the BigQuery profile. Its Destination section shows the Operation: Insert rows (append) (insert) or Upsert by key (MERGE) (upsert), then the Table, and for an upsert the Key columns. Run test shows what the step would do, for example MERGE clinical_rows.api_records ON record_id, without sending anything. Test with a synthetic sample such as TESTPATIENT before you send real messages.
Writing rows
-
Row shapes. The step reads
rowsfrom its parameters if set. Otherwise it reads the step input: a list of objects is the rows, an object with arowslist uses that list (the shape a Data Map withrows[*].columntargets or a CSV parse produces), and a single object is one row. -
Values. A date is sent as an ISO string. Nested objects and lists go to RECORD and REPEATED columns. Send a JSON column's value as a string (
JSON.stringify), and an INT64 or NUMERIC value above 2^53 as a string so it keeps every digit. -
onRowError.fail(default): if BigQuery refuses any row, nothing lands and the step fails, naming each bad row by number, reason and column.skip: the good rows land and the step succeeds withinsertedCountandfailedRows(index,reason,location). Row values never appear in either. -
rowIdColumn. Name a STRING column, and the adapter writes each row's insert ID into it. A row that already has a value there keeps it, and the step result carries a warning. Use it with the view below. -
ignoreUnknownValues.false(default) refuses a row with a field the table does not have.truedrops those fields. -
jsonColumns. The names of the table's JSON columns, for example["resource"]for a FHIR resource. BigQuery's streaming insert takes a JSON column only as JSON text and refuses an object, so the adapter turns an object or array in these columns into JSON text. A value that is already text, and null, are sent as they are. -
checkSchema.truechecks the rows against the table's columns before sending: a field the table does not have (unlessignoreUnknownValues), a missingREQUIREDcolumn, or a list or object in the wrong kind of column fails the step before anything is written, naming the row number and the column. The table's columns are read once and reused for a minute, and read again before a row is refused, so a column you add is picked up at once. An upsert always checks.
Upsert by key
Set the action to upsert and keyColumns to the columns that identify a row, such as ["record_id"], or ["source", "record_id"] for a key of two columns. The step runs one MERGE for its rows:
MERGE `demohealth-prod`.`clinical_rows`.`api_records` AS T
USING (SELECT * FROM UNNEST(@rows)) AS S
ON T.`record_id` = S.`record_id`
WHEN MATCHED THEN UPDATE SET `status` = S.`status`, `updated_at` = S.`updated_at`
WHEN NOT MATCHED THEN INSERT (`record_id`, `status`, `updated_at`) VALUES (S.`record_id`, S.`status`, S.`updated_at`)- Parameters only. The rows travel as one typed query parameter,
@rows, built from the table's own column types. No value is ever written into the SQL text, and every project, dataset, table and column name is quoted. - Checked first. Before the MERGE runs, each row is checked against the table: an unknown field, a missing
REQUIREDcolumn or a missing key value fails the step with the row number and the column, never the value. Key columns must be of a type BigQuery can compare (STRING, INT64, NUMERIC, BIGNUMERIC, BOOL, BYTES, DATE, DATETIME, TIME or TIMESTAMP). - Only what the rows carry. The columns written are the ones the rows have. A column no row carries keeps its value on an updated row.
- One row per key. Rows in one step that share a key are written once, as the last of them, and the step result says how many were folded together.
- Result.
upsertedCount, plusinsertedCountandupdatedCountas BigQuery reports them. - Retries. The same rows give the same table however often they run, so a rate limit, a 5xx or a timeout is retried with the step's retry settings. When the table is busy with other DML (BigQuery's per-table DML queue is full, a concurrent MERGE touched the same rows, or a table DML or update-rate quota is hit), the step is retried after a short randomized wait, so engine replicas do not retry in step; the message is never failed for it.
- One MERGE per table at a time. Each engine replica runs at most
maxConcurrentMergesMERGEs at once on a table (default 1); the rest wait their turn in arrival order, inside the engine, rather than in BigQuery's DML queue. Raise it only when one table takes MERGEs from several workflows that rarely touch the same rows. - JSON columns. An object or list in a JSON column is sent as JSON; no
jsonColumnssetting is needed. - Scale. Each step is one MERGE job for its whole batch. For a large backfill, a batch or a loop sends it as a series of steps, each its own job.
High-volume feeds
BigQuery is built for few large DML statements on a table rather than many small ones. For a feed that sends a steady stream of messages to one table, put a Collector before the upsert step:
flowchart LR
IN["Messages\n(one run each)"] --> MAP["Data map:\nmessage → row"]
MAP --> COL["Collector\n(window: count or time)"]
COL -- "one list per window" --> UP["BigQuery upsert\n(one MERGE per window)"]- The Collector passes each window on as one list, and the upsert step takes a list as its rows, so a whole window is one MERGE, however many rows it holds.
- Close the window by count and time together, for example
maxCount1,000 andwindowMs60,000: a busy feed sends full windows, a quiet one still lands within a minute. - Use
keyPathto keep one window per table or per sender when a workflow writes several. - Rows in one window that share a key are written once, as the last, so a record updated twice in a minute lands as its newest version.
- Replaying or retrying the window's run runs the same MERGE again, which changes nothing that already landed.
Duplicates, retries and replays
With Upsert by key, retries and replays never duplicate a row: the MERGE matches on your key. The rest of this section is about insert.
Each row gets an insertId. It stays the same when the step is retried, and BigQuery drops a row it has seen with the same ID for about a minute. That covers retries only:
- A replay is a new execution, so its rows get new IDs and land again.
- After about a minute, a retry is not deduplicated either.
- An insert that was marked uncertain may have landed. Replaying it is safe only when you read the table through a dedup view.
Give every table a column that identifies the source record, such as the source message control ID, and read it through a view that keeps one row per key:
SELECT *
FROM `demohealth-prod.clinical_rows.observations`
WHERE TRUE
QUALIFY ROW_NUMBER() OVER (PARTITION BY message_control_id ORDER BY ingested_at) = 1Without a business key, set rowIdColumn and partition by that column instead. That removes duplicates from retries, but not from replays, because a replay writes new IDs.
Queries and polls
- Read only. A query or poll step runs one query: it starts with
SELECT,WITHorFROM(pipe syntax).INSERT,UPDATE,DELETE,MERGE, DDL and scripts are refused before anything is sent. - Parameters. Write
:name(as in the SQL database adapter) or BigQuery's own@name, and give the values inparams. The adapter sends them as query parameters, never in the SQL text.{{...}}templates in the SQL and positional?are refused. - Types. A string is STRING, a whole number INT64, another number FLOAT64,
trueorfalseBOOL, andnulla SQL NULL. SetparamTypesfor anything else, for example{ "visit_date": "DATE" }. - Cost.
maximumBytesBilledon the profile (default 10 GiB) caps what one job may scan. A bigger job fails withbytesBilledLimitExceededand bills nothing. A step or message cannot raise it. - Location. Set
locationon the profile for a dataset outside theUSmulti-region. It is sent only when set, and a query that takes more than one round trip reads its results in that location. - Results.
queryreturnsrows,rowCountandtruncated, at mostmaxRowsrows (default 1,000, at most 10,000). TIMESTAMP values come back as ISO strings with microseconds, INT64 values as numbers when they fit and strings otherwise, also inside JSON values. A FLOAT64NaNor infinity is sent and returned as the string"NaN","Infinity"or"-Infinity".
A polling trigger with the action poll runs the workflow once per new row. The adapter binds :cursor (the stored cursor, or cursorInitial before the first row) and :limit:
{
"type": "polling",
"interval": 60000,
"adapterProfileId": "<profile id>",
"action": "poll",
"params": {
"sql": "SELECT id, ingested_at, status FROM encounters WHERE ingested_at >= :cursor ORDER BY ingested_at, id LIMIT :limit",
"cursor": "{{cursor}}",
"cursorInitial": "1970-01-01T00:00:00Z",
"paramTypes": { "cursor": "TIMESTAMP" },
"limit": 500
},
"itemsPath": "rows",
"cursorField": "ingested_at",
"idField": "id",
"startFrom": "beginning"
}- Poll on a column the loader stamps when the row lands, such as
ingested_at, not on a clinical date that can arrive late. - Use
>=and anidField. Rows that share the last cursor value are read again, and the id skips the ones that already ran. - Keep
limit(at most 5,000) above the largest number of rows that share one cursor value, such as one load job's rows stamped with the sameingested_at. Otherwise every poll reads the same full page again and cannot move past it. The poll then runs nothing and records an error that names the limit. A group larger than 5,000 rows always stalls the poll this way; poll on a column with unique values (an increasing id) instead. - The cursor is stored as a string. A numeric cursor column needs
paramTypes{ "cursor": "INT64" }. Whole-number cursors compare exactly, including INT64 values above 2^53. {{cursor}}goes in thecursorparameter only. Written into the SQL, it is refused and the poll records an error.
Paginated REST → BigQuery
The built-in template Paginated REST → BigQuery (Workflows > New > From a template) copies records from a REST API into a table, one row per record. It needs a Generic REST connection for the API, a BigQuery connection for the dataset, and the table api_records in that dataset.
flowchart LR
API["REST API\n(paged GET)"] -- "polling trigger\nor a batch" --> REC["Script:\none record"]
REC --> MAP["Data map:\nrecord → row"]
MAP -- "upsert by key\n(record_id)" --> BQ[("BigQuery\napi_records")]- Source. A polling trigger on the Generic REST connection GETs
/v1/recordsevery 5 minutes and follows every page (paginationmodenext-url: the items underdata, the next page's URL undernext). It sendsupdated_sincewith the newestupdatedAtit has seen (left out on the first poll) and runs the workflow once per new or changed record (idFieldid,cursorFieldupdatedAt). The API must return records inupdatedAtorder. Change the endpoint, query, pagination and cursor field on the trigger to your API's: every pagination mode works. - Script: one record. Takes the record out of the poll's message (
item) or a batch's (row), and fails the run for a record that is not an object or has noid. - Data map: record → row.
idtorecord_id,typetorecord_type,status,patient.mrntopatient_mrn,updatedAttoupdated_at, and the whole record torecord. - Destination. Upsert by key into
api_recordsonrecord_id: a new record inserts a row, a changed record updates its row, and a retry or replay leaves one row per record. A row with an unknown field or norecord_idfails the run before the MERGE, and waits in Messages > Needs action for replay. To keep every version of a record as its own row instead, set the Operation to Insert rows (append).
Create the table with these columns:
record_id STRING REQUIRED, record_type STRING, status STRING, patient_mrn STRING, updated_at TIMESTAMP, record JSONThe BigQuery connection needs roles/bigquery.dataEditor on the dataset (Terraform's edit) and roles/bigquery.jobUser on the job project, because an upsert runs a MERGE job. When you choose Use this template, choose the REST API connection (the poll reads it) and the BigQuery connection. The workflow is created as a draft: dry run it with a synthetic record such as the one below, then deploy.
{
"id": "DEMO-REC-1",
"type": "appointment",
"status": "booked",
"updatedAt": "2026-11-02T14:00:00Z",
"patient": { "mrn": "TEST0001" }
}For a large history, start a batch on the deployed workflow with the same connection, endpoint and pagination. It reads a chunk at a time from a checkpoint, and each row runs the same steps. Because the destination upserts by record_id, the backfill and the poll can overlap: a record read by both still ends as one row.
Access
| Steps | Role |
|---|---|
insert | A custom role on the dataset with bigquery.tables.updateData, bigquery.tables.get and bigquery.datasets.get (Terraform's write) |
upsert | roles/bigquery.dataEditor on the dataset (Terraform's edit), and roles/bigquery.jobUser on jobProject |
query, poll | roles/bigquery.dataViewer on the dataset, and roles/bigquery.jobUser on jobProject |
| Customer-managed key (CMEK) | roles/cloudkms.cryptoKeyEncrypterDecrypter for BigQuery's own service agent, not the engine |
roles/bigquery.dataEditoralso works forinsert, but it lets the engine read every row and create, change or delete tables. Grant it (Terraform'sedit) only where the engine also reads that dataset.- Query and poll steps refuse DML, but that check reads the SQL text only. IAM is the control BigQuery enforces. Grant
dataViewer, notdataEditor, where the engine only reads. - With VPC Service Controls, the job project must be inside the perimeter. Private GKE nodes reach the API through Private Google Access or Private Service Connect.
- Set
kmsKeyNameon the profile to encrypt query result tables with your key.
PHI
- Errors and logs carry only the action, HTTP status, BigQuery's reason, a row number and a column name. Never SQL text, values, rows or BigQuery's own message text.
- Values travel as query parameters, so they stay out of the query text that BigQuery's audit logs record.
- Keep PHI out of table, column and dataset names: they appear in errors, logs and audit records.
- Insert IDs are hashes of the step's retry key, the table and the row number, never of row values.
- BigQuery is covered by Google Cloud's Business Associate Agreement. Use synthetic data such as
TESTPATIENTuntil your healthcare organization has signed it and approved the dataset for PHI.