Sheets & data
Validate emails in BigQuery with a remote function
Verify emails from SQL in BigQuery: a remote function backed by a Cloud Run function that sends each batch of rows to the batch endpoint and returns JSON.
Updated 2026-11-26
This recipe lets you verify email addresses from SQL in BigQuery. A remote function sends batches of rows to a Cloud Run function, which forwards each batch to the API's batch endpoint and answers with one JSON result per row. Then SELECT verify_email(email) FROM ... works like any function, and you store the results in a table. There is no Qelka connector in BigQuery: you deploy the small function below in your own Google Cloud project.
What you need
- A Google Cloud project with the BigQuery, BigQuery Connection, Cloud Run and Secret Manager APIs enabled, and the gcloud and bq command-line tools.
- Permission to create connections and functions in BigQuery, and to deploy to Cloud Run and grant IAM roles.
- A Qelka API key. A
sk_test_key returns simulated results and never spends credits: see Test mode. Use a key restricted tobatchandemailin the dashboard: see Restricted keys.
The examples use a dataset crm in the US multi-region and the region us-central1. A remote function can only call a Cloud Run function in the same location as its dataset, or in a region inside the same multi-region, so adjust both together.
Steps
1. Store the key in Secret Manager
printf '%s' "$QELKA_API_KEY" | gcloud secrets create validation-api-key --data-file=-
The key comes from your shell's environment, so it never lands in a file. Give the Cloud Run function's service account the Secret Manager Secret Accessor role on this secret.
2. Write the Cloud Run function
Create a folder with two files. package.json:
{
"type": "module",
"dependencies": {
"@google-cloud/functions-framework": "^5.0.0"
}
}
index.js:
import { http } from '@google-cloud/functions-framework'
const BATCH_SIZE = 100
const retryable = new Set([429, 500, 502, 503])
async function verifyBatch(emails) {
const items = emails.map((email) => ({ type: 'email', email, mode: 'fast' }))
for (let attempt = 1; attempt <= 3; attempt += 1) {
const response = await fetch('https://api.qelka.com/v1/batch', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.QELKA_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ items }),
signal: AbortSignal.timeout(30000),
})
if (response.ok) return (await response.json()).data
if (retryable.has(response.status) && attempt < 3) {
const retryAfter = Number(response.headers.get('Retry-After'))
await new Promise((resolve) => setTimeout(resolve, (retryAfter > 0 ? Math.min(retryAfter, 10) : attempt * 2) * 1000))
continue
}
const failure = (await response.json().catch(() => null))?.error?.type ?? `http_${response.status}`
throw new Error(`${failure} request ${response.headers.get('X-Request-Id')}`)
}
}
function toReply(result) {
if (result.object === 'error') return { status: 'unchecked', error: result.error.type }
return { status: result.status, reason: result.reason, did_you_mean: result.did_you_mean }
}
http('verifyEmails', async (req, res) => {
const calls = Array.isArray(req.body?.calls) ? req.body.calls : null
if (!calls) {
res.status(400).json({ errorMessage: 'Expected a calls array' })
return
}
const emails = calls.map((call) => (typeof call[0] === 'string' ? call[0].trim() : ''))
const replies = emails.map(() => null)
const indexes = emails.flatMap((email, index) => (email ? [index] : []))
try {
for (let start = 0; start < indexes.length; start += BATCH_SIZE) {
const chunk = indexes.slice(start, start + BATCH_SIZE)
const results = await verifyBatch(chunk.map((index) => emails[index]))
results.forEach((result, position) => {
replies[chunk[position]] = toReply(result)
})
}
} catch (error) {
console.error(`validation skipped: ${error.message}`)
for (const index of indexes) {
if (replies[index] === null) replies[index] = { status: 'unchecked', error: 'api_unavailable' }
}
}
res.status(200).json({ replies })
})
It follows BigQuery's contract. BigQuery posts a JSON body whose calls field is an array of argument lists, one per row, and expects replies, an array of exactly the same length and order. An empty or NULL email gets null. Every other row gets an object with the status, or unchecked when the check did not run.
The function always answers 200, even when the API is down. Google documents that BigQuery retries responses with the codes 408, 429, 500, 503 and 504 and fails the query when the retries run out; answering unchecked keeps the query alive and lets you re-check those rows later. The try block matters for the same reason: an uncaught exception would make the framework answer 500.
mode: 'fast' skips the mailbox check: a whole batch then answers quickly, and BigQuery is not left waiting on slow mail servers. Fast mode catches bad syntax, dead domains and disposable inboxes, but returns unknown with smtp_not_checked instead of deliverable. See the email reference.
3. Deploy it
gcloud run deploy verify-emails \
--source . \
--function verifyEmails \
--base-image nodejs24 \
--region us-central1 \
--no-allow-unauthenticated \
--max-instances 5 \
--update-secrets QELKA_API_KEY=validation-api-key:1
--update-secrets exposes version 1 of the secret as an environment variable. Google recommends pinning a version rather than latest, because environment variables are read when an instance starts. --no-allow-unauthenticated keeps the function private: only principals you grant the invoker role can call it. --max-instances limits how many batches run at once, which keeps you under the API's rate limit. Note the service URL the command prints.
4. Create the connection and grant it access
bq mk --connection --location=US --project_id=my-project \
--connection_type=CLOUD_RESOURCE validation-api
bq show --connection my-project.us.validation-api
The second command shows the connection's serviceAccountId. Give that service account the Cloud Run Invoker role on the function:
gcloud run services add-iam-policy-binding verify-emails \
--region us-central1 \
--member serviceAccount:CONNECTION_SERVICE_ACCOUNT \
--role roles/run.invoker
Replace CONNECTION_SERVICE_ACCOUNT with the serviceAccountId from the previous output.
5. Create the remote function
CREATE FUNCTION `my-project.crm.verify_email`(email STRING)
RETURNS JSON
REMOTE WITH CONNECTION `my-project.us.validation-api`
OPTIONS (
endpoint = 'https://verify-emails-123456789012.us-central1.run.app',
max_batching_rows = 100
);
max_batching_rows caps each request from BigQuery at 100 rows, the most the batch endpoint takes in one request, so each BigQuery request becomes exactly one API call. Without it, BigQuery chooses the batch size and the function splits large batches itself.
Try it:
SELECT
email,
JSON_VALUE(`my-project.crm.verify_email`(email), '$.status') AS status
FROM UNNEST(['disposable@example.com', 'nomx@example.com', 'jane@example.com']) AS email;
With a test key, the statuses are risky, undeliverable and unknown, the last because fast mode does not check the mailbox.
6. Store the results
BigQuery never caches a remote function's result, so a view or a dashboard that calls it would check every address again on each refresh. Keep one row per address instead, and check only addresses you do not have:
CREATE TABLE IF NOT EXISTS `my-project.crm.email_checks` (
email STRING,
result JSON,
checked_at TIMESTAMP
);
DELETE FROM `my-project.crm.email_checks`
WHERE JSON_VALUE(result, '$.status') = 'unchecked';
INSERT INTO `my-project.crm.email_checks` (email, result, checked_at)
SELECT email, `my-project.crm.verify_email`(email), CURRENT_TIMESTAMP()
FROM (
SELECT DISTINCT LOWER(TRIM(email)) AS email
FROM `my-project.crm.signups`
WHERE email IS NOT NULL
AND TRIM(email) != ''
AND LOWER(TRIM(email)) NOT IN (
SELECT email FROM `my-project.crm.email_checks` WHERE email IS NOT NULL
)
LIMIT 5000
);
The LIMIT caps one run at 5,000 checks. Call the function in a plain SELECT like this one: Google documents that BigQuery stops batching when the function sits in a conditional expression or in a MERGE with WHEN [NOT] MATCHED, and then sends one row per request. Schedule the statement as a scheduled query to check new signups every day.
Read the result
$.status |
Meaning | What to do |
|---|---|---|
undeliverable |
Bad syntax, no domain, or a domain that takes no mail | Exclude from sends; $.did_you_mean may hold a fix |
risky |
Disposable inbox ($.reason is disposable) |
Exclude from trials and incentives |
unknown |
Passed the fast checks, or not conclusive | Keep: not a bad address |
unchecked |
The check did not run; $.error says why |
Deleted and retried on the next run |
NULL |
Empty input, nothing was checked | Nothing to do |
For mailbox-level answers on a large backlog, export the distinct emails to CSV and run a bulk job in full mode, then load the result file into email_checks.
Handle errors and rate limits
Nothing is billed on errors. A wrong or restricted key (401, 403) or an empty balance (402) marks a whole batch unchecked with api_unavailable, and the Cloud Run logs show the error type and the X-Request-Id. An item the API cannot check comes back as an error item and only that row is unchecked. 429 rate_limited, 500, 502 and 503 are retried after Retry-After inside the function. A batch counts as one request against the 200 requests per 10 seconds of a key; --max-instances keeps parallel batches below that. See Errors and Rate limits.
Each email costs 1 credit, the same whether the API serves it from its 7-day cache or not, so the email_checks table is what saves credits. Google may resend a batch after a transient error even when the first answer succeeded, so expect a few duplicate checks on large runs.
Related
Frequently asked questions
Does BigQuery cache the results of a remote function?
What does it cost?
Why not let BigQuery call the API directly?
More in Sheets & data
All integrationsPut this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time