1. Understanding the Core Problem & SaaS Architecture
Modern enterprise revenue operations depend on unifying transactional customer relationship data with analytical data platforms. Synchronizing HubSpot CRM data into Google BigQuery presents a distinct architectural challenge: bridging a polymorphic, API-rate-limited, document-style SaaS transactional system with a columnar, distributed analytical warehouse designed for massive append-and-scan workloads. HubSpot organizes data as flexible object graphs—Contacts, Companies, Deals, Tickets, and Custom Objects—interconnected via dynamic association engines. In contrast, BigQuery demands rigid schemas, partitioned physical layouts, and deduplicated record states to execute performant SQL queries cost-effectively.
The primary breakdown in traditional sync pipelines occurs at the intersection of pagination, API throttling, and schema mutability. HubSpot imposes strict rate limits (ranging from 100 to 150 requests per 10-second sliding window for standard tiers, up to specialized enterprise caps) alongside daily call quotas. Naive extraction pipelines attempting full-table scans quickly exhaust API allocations, throw HTTP 429 status codes, and cause upstream failures. Furthermore, HubSpot CRM administrators continuously introduce custom properties, alter picklist enumeration keys, and modify pipeline stages. In BigQuery, an unmanaged schema modification results in schema mismatch aborts, dropped columns, or silent ingestion failures.
Another systemic failure mode involves managing record mutability and associations. HubSpot records are constantly modified; a single marketing automation flow can touch hundreds of thousands of contact properties within minutes. Because BigQuery is an append-optimized Online Analytical Processing (OLAP) database, executing row-level updates directly inside native analytical tables degrades partition health, incurs significant compute overhead, and can hit BigQuery’s partition modification limits (5,000 partition modifications per table per day). A robust integration architecture requires an intermediate, immutable staging layer combined with an idempotent upsert/merge operational pattern.
Finally, HubSpot handles relationships as abstract association IDs rather than standard relational foreign keys. A contact can be associated with multiple deals, multiple companies, and numerous custom engagements. Exporting flat object entities without capturing the underlying association graph limits the analytical value of the warehouse. A production-ready BigQuery pipeline must separate object ingest from association resolution, systematically materializing edge tables to preserve entity relationship integrity for advanced cohort modeling, multi-touch attribution, and predictive lifetime value (LTV) calculations.
2. Key Features & Comparison Table
Selecting the optimal architectural approach for moving HubSpot data into BigQuery depends on throughput requirements, latency tolerance, development resources, and total cost of ownership. The comparison below evaluates the four industry-standard data ingestion patterns.
| Architecture Pattern | Sync Latency | Schema Drift Resilience | Implementation Complexity | Cost Profile & Maintenance |
|---|---|---|---|---|
| Managed SaaS ELT (e.g., Fivetran, Stitch) | 15 mins – 24 hours | High (Automatic handling of new columns and type casting) | Very Low (Turnkey connection via OAuth) | High Monthly Subscription; Low DevOps Maintenance |
| Custom Cloud-Native ELT (Cloud Run + GCS + BQ) | Micro-batch (5 mins) to Hourly | Medium (Requires custom JSON/schema migration scripts) | High (Requires custom microservices and IaC setup) | Extremely Low Compute Cost; Medium DevOps Maintenance |
| HubSpot Webhook Stream + Cloud Pub/Sub | Near Real-Time (< 5 seconds) | Low (Payload discrepancies can break streaming consumers) | High (Must implement stateful deduplication & reordering) | Usage-based GCP pricing; High Monitoring Overhead |
| Google Cloud Data Fusion (CDAP Connector) | Scheduled Batch (e.g., Hourly) | Medium (Configurable error handling inside visual nodes) | Medium (Visual pipeline configuration) | High Minimum Cluster Idle Cost; Low Pipeline Code |
3. Step-by-Step Practical Integration & Solution
The following technical blueprint details the construction of a custom, highly scalable, cost-effective serverless extraction and load pipeline using Python, Google Cloud Storage (GCS), and Google BigQuery. This pattern extracts updated data incrementally via the HubSpot CRM v3 Search API, stages it as newline-delimited JSON (NDJSON) in GCS, loads it to an unpartitioned landing table, and executes an atomic BigQuery MERGE operation.
-
Configure HubSpot Private App Authentication and Scopes
HubSpot has deprecated standalone API keys in favor of Private Apps. Create a scoped application to establish least-privilege enterprise access.
- Navigate to HubSpot Settings > Integrations > Private Apps and click Create a private app.
- Under the Scopes tab, configure the following granular read permissions:
crm.objects.contacts.readcrm.objects.companies.readcrm.objects.deals.readcrm.schemas.contacts.read(required to validate schema modifications)
- Generate the token, then securely store it in Google Cloud Secret Manager under the secret name
HUBSPOT_API_TOKEN.
-
Initialize BigQuery Datasets and Tables
Construct a multi-layer schema separating raw staging payloads from curated, production-ready tables. Run the following DDL statements in the BigQuery Console:
- Create the operational datasets:
CREATE SCHEMA IF NOT EXISTS `corp-data-lake.hubspot_raw` OPTIONS(location="US");CREATE SCHEMA IF NOT EXISTS `corp-data-lake.hubspot_curated` OPTIONS(location="US"); - Create the production target table with date partitioning and clustering keys for optimal scan performance:
CREATE TABLE IF NOT EXISTS `corp-data-lake.hubspot_curated.contacts` (
id STRING NOT NULL,
email STRING,
firstname STRING,
lastname STRING,
hs_calculated_phone_number STRING,
lifecyclestage STRING,
createdate TIMESTAMP,
lastmodifieddate TIMESTAMP,
properties_json STRING,
_synced_at TIMESTAMP
)
PARTITION BY DATE(lastmodifieddate)
CLUSTER BY id, email; - Create the transient staging table (truncated before every load job):
CREATE OR REPLACE TABLE `corp-data-lake.hubspot_raw.contacts_staging` (
id STRING NOT NULL,
properties STRING,
createdAt TIMESTAMP,
updatedAt TIMESTAMP,
archived BOOLEAN
);
- Create the operational datasets:
-
Build the Incremental Ingestion Logic
The pipeline relies on HubSpot’s CRM Search API (
POST /crm/v3/objects/{objectType}/search) to fetch only records modified since the high-watermark timestamp stored from the previous execution.- Query BigQuery to retrieve the dynamic high-watermark:
SELECT COALESCE(MAX(lastmodifieddate), TIMESTAMP('1970-01-01')) AS watermark FROM `corp-data-lake.hubspot_curated.contacts`; - Formulate the search payload to retrieve modified records in increments of 100 (HubSpot search API limit per page):
{
"filterGroups": [{
"filters": [{
"propertyName": "lastmodifieddate",
"operator": "GT",
"value": "1704067200000"
}]
}],
"sorts": [{"propertyName": "lastmodifieddate", "direction": "ASCENDING"}],
"properties": ["email", "firstname", "lastname", "lifecyclestage", "createdate", "lastmodifieddate", "hs_calculated_phone_number"],
"limit": 100,
"after": 0
} - Handle cursor pagination: Check the response object for
paging.next.after. If present, pass this string/integer into the subsequent payload’safterproperty. Loop untilpagingis null. - Implement exponential backoff logic: Intercept HTTP status code 429. When encountered, read the
Retry-Afterheader (or default to(2^attempt) + random_jittermilliseconds) and back off to preserve API quotas.
- Query BigQuery to retrieve the dynamic high-watermark:
-
Stage Ingestion Payloads in Google Cloud Storage
Avoid loading data directly via the BigQuery streaming API to prevent streaming costs and partition modifications limits. Instead, stream the records into newline-delimited JSON files stored inside Google Cloud Storage.
- Structure objects into lines: Serialize each contact into a single NDJSON line. Ensure the raw
propertiesobject is converted to an escaped JSON string if dynamic fields are present. - Write batch files using partitioned URIs:
gs://corp-hubspot-ingest-bucket/contacts/year=2024/month=03/day=28/extract_1711612800.ndjson
- Structure objects into lines: Serialize each contact into a single NDJSON line. Ensure the raw
-
Trigger BigQuery Load Job into Staging
Execute an external BigQuery Load Job to transfer data from Cloud Storage to the staging table. This operation is free under standard BigQuery batch ingestion quotas.
- Configure the load job parameters:
- Source Format:
NEWLINE_DELIMITED_JSON - Write Disposition:
WRITE_TRUNCATE(refreshes staging table) - Autodetect Schema:
FALSE(use static staging schema for deterministic type coercion)
- Source Format:
- Execute the load job using the Python Google Cloud BigQuery client:
from google.cloud import bigquery
client = bigquery.Client()
job_config = bigquery.LoadJobConfig(
source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE
)
load_job = client.load_table_from_uri(
"gs://corp-hubspot-ingest-bucket/contacts/year=2024/month=03/day=28/*.ndjson",
"corp-data-lake.hubspot_raw.contacts_staging",
job_config=job_config
)
load_job.result()
- Configure the load job parameters:
-
Execute the Idempotent Atomic Merge Operation
Perform an atomic merge from the staging table to the curated target table. Parse out top-level columns while retaining the unparsed payload inside a native JSON or STRING column for downstream parsing flexibility.
- Execute the following SQL command within the ingestion pipeline:
MERGE INTO `corp-data-lake.hubspot_curated.contacts` AS target
USING (
SELECT
id,
JSON_VALUE(properties, '$.email') AS email,
JSON_VALUE(properties, '$.firstname') AS firstname,
JSON_VALUE(properties, '$.lastname') AS lastname,
JSON_VALUE(properties, '$.hs_calculated_phone_number') AS hs_calculated_phone_number,
JSON_VALUE(properties, '$.lifecyclestage') AS lifecyclestage,
PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*SZ', JSON_VALUE(properties, '$.createdate')) AS createdate,
PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*SZ', JSON_VALUE(properties, '$.lastmodifieddate')) AS lastmodifieddate,
properties AS properties_json,
CURRENT_TIMESTAMP() AS _synced_at
FROM `corp-data-lake.hubspot_raw.contacts_staging`
WHERE archived IS FALSE
-- Deduplicate within staging window if multiple revisions were captured
QUALIFY ROW_NUMBER() OVER(PARTITION BY id ORDER BY updatedAt DESC) = 1
) AS source
ON target.id = source.id
WHEN MATCHED AND source.lastmodifieddate > target.lastmodifieddate THEN
UPDATE SET
email = source.email,
firstname = source.firstname,
lastname = source.lastname,
hs_calculated_phone_number = source.hs_calculated_phone_number,
lifecyclestage = source.lifecyclestage,
lastmodifieddate = source.lastmodifieddate,
properties_json = source.properties_json,
_synced_at = source._synced_at
WHEN NOT MATCHED THEN
INSERT (id, email, firstname, lastname, hs_calculated_phone_number, lifecyclestage, createdate, lastmodifieddate, properties_json, _synced_at)
VALUES (source.id, source.email, source.firstname, source.lastname, source.hs_calculated_phone_number, source.lifecyclestage, source.createdate, source.lastmodifieddate, source.properties_json, source.source._synced_at);
- Execute the following SQL command within the ingestion pipeline:
-
Extract and Map Association Graphs
To preserve cross-object relational mapping, extract associations independently using the HubSpot Association API (
GET /crm/v3/associations/{fromObjectType}/{toObjectType}/batch/read).- Query associations between Contacts and Companies in batches of 1,000 IDs.
- Write association outputs directly to an association edge table:
CREATE TABLE IF NOT EXISTS `corp-data-lake.hubspot_curated.association_contacts_companies` (
contact_id STRING NOT NULL,
company_id STRING NOT NULL,
association_type STRING,
_synced_at TIMESTAMP
)
CLUSTER BY contact_id, company_id; - Use these edge tables inside BigQuery views to easily execute multi-table joins without duplicating primary contact attributes.
4. Security, Compliance & Best Practices
Deploying customer data pipelines requires rigorous operational controls to prevent data exposure, maintain compliance with regulatory frameworks such as GDPR and CCPA, and control cloud infrastructure costs.
-
Enforce Column-Level Access Control for PII:
Customer data synced from HubSpot frequently contains Personally Identifiable Information (PII) including email addresses, phone numbers, and direct billing identifiers. Apply BigQuery Policy Tags within Google Cloud Data Catalog directly to the sensitive columns (e.g.,
email,hs_calculated_phone_number). Mask these values dynamically for analytical users who do not have cryptographic or explicit unmasked read entitlements. -
Automate GDPR/CCPA “Right to Be Forgotten” Deletions:
Incremental syncs based on
lastmodifieddatedo not capture hard-deletions natively because a deleted record no longer emits a modified timestamp. Implement a daily synchronization task consuming the HubSpot Archival API endpoint or configure HubSpot Webhooks for thecontact.deletionevent. When triggered, execute an automated deletion or tombstone query:DELETE FROM `corp-data-lake.hubspot_curated.contacts` WHERE id IN UNNEST(@deleted_contact_ids); -
Service Account Isolation and Least Privilege:
Do not use broad compute or project-editor service account credentials. Create a dedicated service account specifically for this pipeline (e.g.,
sa-hubspot-pipeline@corp-data-lake.iam.gserviceaccount.com) assigned strictly with the following roles:roles/bigquery.dataEditor(restricted to datasetshubspot_rawandhubspot_curated)roles/bigquery.jobUser(project-level permission to run merge and load jobs)roles/storage.objectAdmin(restricted exclusively to the staging GCS bucket)roles/secretmanager.secretAccessor(restricted exclusively to the HubSpot API token secret)
-
Defend Against Undocumented Schema Drift:
Avoid auto-generating BigQuery columns dynamically from HubSpot property keys without validation. Unchecked user creation of properties in HubSpot can cause a single contact to exceed BigQuery’s maximum row width or introduce illegal characters in column names (HubSpot allows characters that BigQuery rejects, such as hyphens and special symbols). Dump variable or unmapped properties into a single semi-structured native
JSONcolumn, and use BigQuery’s nativeJSON_EXTRACTfunctions to normalize these fields within materialized views. -
Cost Optimization and Quota Governance:
Avoid writing frequent micro-batches directly to BigQuery using the streaming insert API (
tabledata.insertAll). Streaming ingest generates high operational costs and fragments underlying physical storage. Batch your intermediate syncs into Cloud Storage and load them into BigQuery at intervals of 15 to 60 minutes. This preserves native load job quotas (1,500 table loads per day per table) while reducing pipeline run costs to near zero.
▶ Watch the Quick Shorts Recap