Acme Marketing Architecture

WP0b PoC brief: HubSpot adapter

WP0b PoC brief: HubSpot adapter

Implementation brief for the two throwaway proofs of concept in roadmap WP0b: the HubSpot adapter contract built once as .NET 10 on Azure Functions and once as a Fabric Python notebook, measured against the criteria in ADR 8. Written 2026-10-26 from the architecture documents plus a research pass on HubSpot's current limits; every figure below was checked against HubSpot's or Microsoft's documentation on that date unless marked otherwise.

1. Purpose and boundaries

2. HubSpot limits that shape the code

Limit Value Source and date Consequence in the adapter
Burst, private app 100 requests per 10 s (Free/Starter); 190 per 10 s (Professional/Enterprise); 250 per 10 s with the API limit increase (one HubSpot page still says 200) HubSpot usage guidelines, 2026-10-26 Per app, not per endpoint: every function that calls HubSpot draws on one bucket (§3)
Daily, account 250,000 / 625,000 / 1,000,000 by tier; +1,000,000 per limit increase, at most two; shared by all apps on the account; resets at the portal's midnight Same Shared ledger counter with a reserve; other integrations on the account eat the same allowance (B2)
CRM search 5 requests per second per account (raised from 4; the research paste says 4); 10,000 total results per query; paging past 10,000 returns 400; page size at most 200; request body at most 3,000 characters; archived objects never appear; newly written objects can take moments to be indexed HubSpot CRM Search API page and changelog, 2026-10-26 Separate per-second bucket (until the test portal shows whether a search also draws on the per-app 10-second limit, charge it to both buckets, finding C27); keyset paging on hs_object_id inside the window with one sort rule; count per window for reconciliation; limit: 200; property list may not fit the body (§5); safety lag before window_end; archived sweep uses the list endpoint
Batch read 100 ids per request HubSpot CRM object batch endpoints Chunk ids by 100
Associations API Own limits: 100 per 10 s (Free/Starter), 150 per 10 s (Professional/Enterprise), 200 with the increase; 500,000 per day; batch read takes up to 1,000 ids and returns every association of each id with typeId, category, label; the API is now published under a date version (/crm/associations/2026-09/...) HubSpot associations v4 page, 2026-10-26 Third bucket; search and batch read return no associations, so a separate batch call per 1,000 ids per object pair; pin the API version in the client
GraphQL endpoint 30,000 points per query, execution stops at the cap and returns what was fetched under HTTP 200; 500,000 points per rolling minute and 300,000,000 per rolling day per account, then 429; 300 points per internal request, 30 per object, 3 per property with a value HubSpot GraphQL page, 2026-10-26 Not used (§6)
Webhook retries HubSpot retries failed deliveries, reportedly up to 10 attempts over 24 hours Not verified The receiver answers 200 within milliseconds; retries are irrelevant to correctness because polling is the truth
Rate-limit feedback Response headers X-HubSpot-RateLimit-Daily, -Daily-Remaining, -Interval-Milliseconds, -Max, -Remaining; GET /account-info/v3/api-usage/daily/private-apps reports daily use per private app Usage guidelines, 2026-10-26 Feed source_reported_remaining in api_budget; shrink the local bucket when the header says the real one is lower

3. Request budget and concurrency (decided in ADR 8)

HubSpot's limits are per app and per account. Several processes call HubSpot: the incremental extractor, the nudge worker, the reconciler and archived sweep, and during WP1 the historical loader. Without coordination they would 429 each other and any other integration on the account. The architecture's rule is static shares plus one in-flight instance per share, no shared infrastructure:

Caller Share of the per-app burst (Professional/Enterprise, 190 per 10 s) Share of search (5 per s) Associations (150 per 10 s) Concurrency pinning
Incremental extractor 120 3 120 The pipeline runs HubSpot objects sequentially (ForEach with batch count 1); one Web activity in flight
Nudge worker 40 0 (batch read only) 0 ingest-nudges is session-enabled with one session id per portal, and the session lock admits one receiver across all instances (the host.json maxConcurrentSessions and maxConcurrentCalls settings do not apply to a batched session trigger, finding C7); size maxMessageBatchSize and the lock duration instead; messages are received in batches and grouped by object type into batch reads of 100. The nudge worker stays on Functions in both variants (Lead Architect, finding C3)
Reconciler and archived sweep 10 1 0 Scheduled serially by the pipeline
Historical loader (WP1) Takes the extractor's share while the extractor is paused 0 120 Pipeline loop over partitions
Headroom 20 1 30 Absorbs retries and HubSpot's own UI and workflows

4. Resilience policy (both variants)

Situation Action
429 with Retry-After Sleep exactly that, then retry; the header beats any computed backoff
429 without the header, 5xx, timeout, connection reset Full-jitter backoff: sleep = random(0, min(8 s, 0.5 s × 2^attempt)), at most 5 attempts per request (ceilings 1, 2, 4, 8 s, finding C13); then the run step fails with the cursor preserved (ledger failed); the next schedule or the operator resumes from the cursor. No DLQ on the polling path: polling is idempotent and repeats
429 whose body says the daily limit (HubSpot's error body carries a category and policy name distinguishing the daily from the 10-second limit; verify the exact field names against a live 429) Open the caller's circuit until the portal's midnight plus one minute with no probe, recorded as breaker_state.open_reason = daily_limit; any other open circuit goes half-open after 60 s (finding C30); alert; do not retry
10 or more 429s within a rolling minute per caller, counted across requests and runs (the breaker state is persisted in the adapter state, so the next scheduled run starts half-open; a per-request count can never reach it, finding C13), or more than half of the requests in a minute failing with 5xx Open the circuit for 60 s; half-open with a single cheap probe (GET /crm/v3/objects/contacts?limit=1); close on success, reopen on failure; alert when open
4xx other than 429 (400 body too long, 401/403 scope, 404) No retry; fail the step; log the status and HubSpot's category field, never the payload
Nudge message fails 5 deliveries Service Bus dead-letters it (max delivery count 5); alert on DLQ depth; the records are still caught by the next poll, so the DLQ is diagnostic, not a loss
Webhook receiver Validate X-HubSpot-Signature-v3 with the timestamp window against the configured public URL, map subscriptionType and objectTypeId to the registry object through webhook_object_type, enqueue {object, objectId, occurredAt, subscriptionType, portalId} with the portal session id (unmapped events are dropped and counted, finding C29), answer 200; never call HubSpot from the receiver

Idempotency: a page file is written before its cursor is committed; a run_id fixes its windows and split plan at first start, a rerun with the same run_id reads them from the ledger and overwrites the same page files, and only a new run_id recomputes from the watermark (finding C23); a HubSpot window marked truncated (offset mode only) fails the run with error_class = truncated and its watermark does not move; only Google Ads change_event windows are split and rerun (finding C28); nothing is marked landed while any window is truncated (ADR 5).

5. Extraction algorithm for contacts

  1. Windows: from the watermark, at most max_windows_per_run windows of window_size_minutes, ending no later than now − safety_lag (5-minute safety lag for the search index); the watermark advances after each landed window, so a catch-up is several short runs; a gap longer than historical_threshold_days goes to mode = historical through the list endpoint, which carries the property list on the call only while the URL stays under about 2,000 characters and otherwise lists ids and batch-reads properties in chunks of 100; very large portals use the async CRM export (finding C33; the URL limit is on the test-portal list). window_key = {source}/{object}/{start}/{end} with UTC timestamps yyyy-MM-ddTHH:mm:ss.fffZ, half-open (finding C21). A run_id fixes its windows and split plan at first start; a rerun with the same run_id reads them from the ledger (finding C23).
  2. Count (the extractor's own call, on its own search share; logged as windows[].total for reconciliation, finding C32): search with the window filter and limit: 1; read total. No window halving and no list-endpoint fallback: keyset paging never pages past the cap.
  3. Page (keyset; Lead Architect, finding C2): filter hs_lastmodifieddate GTE window_start AND LT window_end AND hs_object_id GT last_id, one sort rule hs_object_id ASC (HubSpot accepts a single sort, finding C1), limit: 200, no after; the cursor is the last id; each request is a fresh query, so a record modified mid-run cannot shift a page. Verify on the live portal that hs_object_id accepts GT; object_registry.paging_mode keeps the offset mode selectable until then.
  4. Properties: request the object's property list in the search body when the body stays under 3,000 characters; otherwise search for ids and hs_lastmodifieddate only and batch-read properties in chunks of 100. Measure both paths once; the request count differs.
  5. Associations: for every 1,000 contact ids, one associations batch read per pair (contacts → companies in the PoC); land the response verbatim, one line per from result with its nested to[] list, as object associations_contacts_companies; the Bronze loader or the Silver mapping flattens it to {from_id, to_id, type_id, category, label} (finding C20). The batch read returns the full current set per id, so Silver can diff and end removed associations.
  6. Landing: Files/landing/hubspot/contacts/{yyyy}/{MM}/{dd}/{run_id}/page-00001.jsonl … (one record per line, as the contract says; finding C6) plus manifest.json with rows, pages, cursor_end, truncated, requests_used, the windows actually used, the properties requested, op, property_path and paging_mode; the same layout for the associations object.
  7. Cursor commit after each page file (Table Storage in the Functions variant, the control schema in the notebook variant).
  8. Reconciler count: the reconciler process makes its own search with limit: 1 per window on its own search share, separate from the extractor's in-run count (finding C32).
  9. Nudge path: receive a batch of messages, group ids by object type, batch-read 100 at a time, land with op=webhook_nudge, complete the messages; abandon on failure so Service Bus redelivers.

6. What the research proposed and what the architecture does with it

Research proposal Verdict Why
Durable queue (RabbitMQ or SQS) between a webhook ingress and rate-aware workers Adopted, as Azure Service Bus Standard, already the design ADR 7, ADR 8; sessions give the single-consumer guarantee
Separate "ingestion microservice" in front of the queue Already present as the webhook receiver function Nothing else is inbound; the sources are polled
Distributed Redis token bucket shared by all workers Fallback only Static shares with one in-flight instance per share need no extra service; Redis is adopted only if the PoC proves a share starves (§3)
Exponential backoff with full jitter, circuit breaker, DLQ Adopted, already in ADR 5; parameters fixed in §4 Thundering-herd argument holds; the daily-limit case needs the breaker, the secondly case needs the jitter
"Write-ahead key map" instead of the search endpoint Not applicable The adapter never searches by text; it searches by last-modified window. Internal keys are (source, source_id) in Silver
Chunk batch updates by 100 Already the contract for batch read; associations chunk by 1,000 Integration contracts
Search limited to 4 requests per second Corrected to 5 per account HubSpot changelog and current docs
HubSpot GraphQL endpoint for extraction Rejected (recorded in ADR 3) Stops at 30,000 points and returns a partial result under HTTP 200; the account-wide point pool is shared with CRM UI extensions; the endpoint is built for CMS data-driven content; the 500-record cap in the research paste was not verified
Public OAuth app at 110 requests per 10 s per portal Not applicable The platform uses a standalone private app (ADR 10)

7. Acceptance test and measurements

Same test for both variants, run against the test portal:

  1. A 15-minute window with fewer than 10,000 changes: lands, manifest correct, watermark advances.
  2. A window with more than 10,000 matches (bulk-edit a property on more contacts than the cap, or shrink the cap in configuration): keyset paging reads them all, no rows lost versus the list endpoint; test 2b: a record modified while the run pages is neither skipped nor duplicated.
  3. A forced 10-second 429 (set the share above the real limit for one run): backoff with jitter observed, Retry-After honoured, cursor preserved, no duplicate page files.
  4. A simulated daily-limit error (stub or configuration): circuit opens until the configured reset, alert raised, no further calls.
  5. Nudge path during an extractor run: both complete, HubSpot returns no 429 (the shares hold), nudged records landed with op=webhook_nudge.
  6. Associations for the window landed and reconciled against a direct read of ten sampled contacts.

Record for ADR 8: engineering days per variant; end-to-end latency for test 1 (trigger to manifest); behaviour in tests 3 and 4; cost per day (Function execution charges versus CU-seconds in the Capacity Metrics app); lines of operational code (state, retries, secrets, limiter); unit tests runnable in CI; requests used per 1,000 contacts for the two property paths in §5 step 4 and for associations; whether any share starved in test 5; two live checks for the notebook variant: library packaging for the Python kernel (%pip of a wheel from Files/ or notebook resources, inline installation enabled in pipeline runs, finding C14) and the abfss write of control tables with a storage token (finding C15).

8. Ask, do not invent

These change the numbers above and are not known; they are already on the business list in open questions:

9. Google Ads slice (added 2026-10-26 at the architect's request)

Purpose: prove the second source on the same adapter skeleton and measure reuse. The engineering days for Google Ads after HubSpot are the pluggability number the architecture claims (adding a source).

Scope

One customer account under the manager account, through the same contract and landing layout:

Call GAQL Notes
extract_full(campaign) SELECT campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign_budget.amount_micros FROM campaign One snapshot file; the Silver diff is out of scope
extract_incremental(campaign_performance, window) SELECT campaign.id, segments.date, metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions, metrics.conversions_value FROM campaign WHERE segments.date BETWEEN '{start}' AND '{end}' through GoogleAdsService.SearchStream Window = trailing 30 days; one file per customer per window under a customer={id} path segment, customer_id in the manifest (finding C19); money in micros; dates in the customer's own time zone
extract_incremental(change_event, window) SELECT change_event.change_date_time, change_event.change_resource_type, change_event.resource_change_operation, change_event.changed_fields FROM change_event WHERE change_event.change_date_time >= '{start}' AND change_event.change_date_time < '{end}' ORDER BY change_event.change_date_time LIMIT 10000 10,000 rows back means truncated: the adapter halves the window and reruns inside the same run, down to min_window_seconds (finding C36). Leave change_event.user_email out; it is personal data and the PoC does not need it
count(campaign_performance, window) Rows per segments.date from the same query Reconciliation compares row counts per day between landing and Silver

Customers are enumerated once through customer_client with login-customer-id set to the manager id; the PoC runs one customer, the code loops serially. Each customer has its own watermark and windows (partition = customer_id), so one failing or throttled customer does not hold back the others (finding C34). Enumeration also reads customer.time_zone per customer and stores it; change_event.change_date_time and segments.date are interpreted in that zone, not in a per-source zone (finding C26). Each truncation retry costs one extra operation per halving level, negligible at hourly cadence. The landing folder date is the UTC date of the window start, not a business date.

Limits that shape the code (verified 2026-10-26)

Limit Value Consequence
Access levels Developer tokens were sunset on 2026-09-09; access is per Google Cloud project. Explorer: 2,880 operations per day on production accounts, automated approval. Basic: 15,000 per day, brand verification required. Standard: unlimited, manual audit, about 10 business days Explorer is enough for the PoC; production needs Basic; Standard only if a day exceeds 15,000 operations
What counts One Search or SearchStream request = one operation regardless of rows or batches; pages with a valid next_page_token are free; rejected requests still count Prefer SearchStream; a day of the full design is about 36 operations per customer (7 entity snapshots, 5 performance queries, 24 hourly change_event pulls), so 100 customers fit Basic
Errors RESOURCE_EXHAUSTED for the daily quota and for oversized responses (gRPC 8, HTTP 429); RESOURCE_TEMPORARILY_EXHAUSTED for short-term limits, retry with exponential backoff and jitter Daily: open the circuit, probe hourly (the quota is a sliding 24-hour window), alert. Temporary: full jitter from 2 s doubling, cap 8 s, 5 attempts (ADR 5)
Response size 64 MB per response Fewer fields or a narrower date window; never more customers per query
change_event Past 30 days only; LIMIT 10000 mandatory Truncation handling above; the pull is hourly in production so the cap is never reached by design

Auth: OAuth 2.0 refresh token for a dedicated Google account with read-only access on the manager account, client id and secret of the Google Cloud project, all in Key Vault; developer token: Google's access-levels page says tokens were sunset on 2026-09-09 while its REST authorization page still requires the developer-token header (finding C5), so keep the Key Vault entry, send the header when source_registry.developer_token_ref resolves, and confirm on the first live call. Request budget: no 10-second bucket exists in the documentation; the controls are the daily operations ledger (api_budget, 10% reserve) and serial execution per customer.

Acceptance tests and measurements

  1. Trailing 30-day performance pull for one customer lands with one row per campaign per day; row count per day matches a Search of the same query.
  2. The same window pulled the next day: the diff lists the dates whose metrics moved (restatement evidence for the metrics.restated tolerance in ADR 3).
  3. change_event with the cap lowered in configuration to 10: truncated set, window halved, rerun complete.
  4. Stubbed RESOURCE_TEMPORARILY_EXHAUSTED then RESOURCE_EXHAUSTED: backoff observed, then circuit open and alert.

Record: engineering days for the slice (reuse of the HubSpot skeleton: landing, manifest, cursor, limiter, ledger); operations used per customer per day; latency for test 7; REST googleAds:searchStream through requests and HttpClient is accepted as the reference client for built adapters, so no client-library measurement (architecture assistant's call, finding C10).

Test data caveat: Google Ads test accounts serve no ads, so performance metrics come back empty; tests 7 and 8 need a production read-only customer, which depends on B4. Without it, run the mechanics on empty metrics and say so in the results.

Sources