Why this matters
Every advertising decision in a business rests on two questions: did the ad platforms actually learn which buyers converted, and do the revenue numbers on the dashboard match real money in the shop's ledger? Browser tracking tags lose a large share of conversions to ad blockers, dropped mobile tabs and short cookie lifetimes, which starves Meta and Google's bidding algorithms of feedback. At the same time, ad managers grade their own homework and routinely claim the same customer's purchase twice, inflating reported revenue well above actual bank deposits. This lesson explains how this repository sends consent-gated, platform-exact server-side events to Meta and Google while computing honest integer KPIs that never confuse platform claims with store truth.
The ideas
Why browser pixels lose signal, and what server-side signals add
When a small online shop starts advertising, it usually installs a browser pixel such as the Meta Pixel or a Google tag inside its website theme. Whenever a shopper loads a checkout confirmation page, the browser fires an HTTP request straight to Meta or Google. That setup is quick, yet fragile: privacy-focused browsers shorten third-party cookies to days or hours, ad blockers cancel tracking scripts completely, and shoppers frequently close a mobile tab right after paying before the thank-you page finishes loading. Losing 25 to 40 percent of real purchases makes profitable campaigns look weak and deprives automated bidding of its best examples.
A server-side signal solves the transport problem by sending the same conversion event from a backend server to Meta or Google over HTTPS. Browser blockers cannot intercept a server-to-server call, and confirmed store orders or CRM sales still fire even if the customer closed their phone. Pairing the browser pixel with a server-side event that carries the exact same event id and event name lets the platform collapse both messages into one conversion through deduplication.
In plain words
Server-side delivery is strictly about reliability and control, never about bypassing user privacy. Every legal and platform consent requirement that applies in the browser applies with equal force on the server.
One event's four-stage path
Sending events directly from a storefront plugin to two different ad platforms creates brittle coupling: if Meta is slow, checkout hangs; if two plugins normalise phone numbers differently, match rates drop silently; if a bug logs a request body, raw customer e-mail addresses spill into log files. Separating the pipeline into four stages gives each stage one crisp responsibility:
Storefront page (gd-1p.js)
| raw event + consent flags
v
1. Edge collector (apps/collector)
| sanitise URL -> normalise & SHA-256 hash PII -> drop raw PII
| HMAC-SHA256 sign raw request body
v
2. Signed API ingest (POST /v1/ingest/events)
| verify HMAC -> check consent per destination -> deduplicate
| commit tracking_events + tracking_event_keys in one transaction
v
3. PostgreSQL storage (workspace RLS)
| queued rows (consented) + skipped_no_consent rows (audit trail)
v
4. Isolated dispatch process (apps/api/src/dispatch-main.ts)
| lease batch -> fetch connection -> dispatch Meta CAPI / Google DM
v
Meta Conversions API (test mode by default) | Google Data Manager (validateOnly: true)Splitting collection from dispatch keeps page loads fast, keeps raw personal data out of the database, isolates platform credentials inside a least-privilege dispatch process, and lets failed calls wait quietly for retry without losing events.
Normalising personal data differently per platform before hashing
Meta and Google match server-side events to logged-in user accounts by comparing SHA-256 digests of personal details such as e-mail addresses, phone numbers, names and cities. As explained in Lesson 5, SHA-256 exhibits the avalanche effect: changing one single character — a trailing space, a capital letter, a leading + sign or a Turkish accent — produces a completely unrelated 64-character hex string. If our server hashes a slightly different canonical string than Meta or Google holds in its index, the match fails silently with zero error message.
Three normalisation rules trip up almost every naive implementation:
| Identifier | Meta Conversions API (v27.0) | Google Ads Data Manager API (v1) | Why sharing one hash fails |
|---|---|---|---|
| Phone number | Digits only, country code included, no leading + (example: 905321234567) | Strict E.164 with leading + (example: +905321234567) | Hashing with + breaks Meta; hashing without + breaks Google |
| Gmail address | Trim, lower case, UTF-8 NFC (example: a.b+shop@gmail.com) | Trim, lower case, UTF-8 NFC, plus strip dots and +alias before @ on gmail.com and googlemail.com (example: ab@gmail.com) | Google normalises Gmail aliases to one mailbox hash before matching |
| Turkish names and cities | Spec-exact UTF-8 NFC lower case first (example: şişli, ibrahim), optional variants behind it in the array | Spec-exact UTF-8 NFC lower case (example: şişli), keeping accents intact | Folding ş to s before the primary hash destroys UTF-8 matches |
Look closely at the first row. Split phone hashing is non-negotiable: one customer phone number must produce two distinct SHA-256 digests at the edge, one without + for Meta and one with + for Google (and later TikTok). Likewise, Gmail alias stripping removes dots and +tag suffixes only on gmail.com and googlemail.com domains, leaving corporate or Turkish ISP addresses untouched because non-Gmail servers treat dots as significant characters.
Turkish text introduces a subtler trap around dotted İ and dotless ı. Standard JavaScript .toLowerCase() turns capital dotted İ into i plus a separate combining dot mark (i\u0307), while aggressive ASCII folding strips ç, ğ, ı, ö, ş and ü completely. Following owner decision OD-16, every field first computes a spec-exact hash matching the platform's own published documentation in NFC UTF-8, and for Meta name and city arrays optionally appends a Turkish-locale variant and a legacy ASCII-folded variant behind it when their digests differ.
Hashing at the edge and why hashed never means consent-free
With hash-on-ingest, the edge collector runs PII normalisation and SHA-256 hashing in memory the instant an event arrives, strips query strings and fragments from URLs, and throws away the raw strings before forwarding anything over the network. No raw customer e-mail or phone number ever enters PostgreSQL or application logs.
Even so, hashing does not turn personal data into anonymous data. Under Turkey's KVKK and Europe's GDPR, a SHA-256 digest of a phone number or e-mail address is still pseudonymous personal data because an ad platform matches it straight back to a real person. Sending hashed identifiers without permission is still an unlawful transfer.
A fail-closed consent gate therefore sits ahead of every destination:
- Meta Conversions API requires explicit marketing consent (
consent_marketing === true). - Google Ads Data Manager API requires both
consent_marketing === trueand Google Consent Mode v2consent_ad_user_data === "GRANTED".
Whenever a visitor declines, withdraws or omits consent — or grants marketing consent while denying ad_user_data — the server stores the event with status skipped_no_consent and makes zero outbound network calls for that destination. Keeping the skipped row gives workspace owners proof that the gate is active without leaking personal data.
Meta Conversions API and Google Data Manager API specifics
Although both platforms accept server-side conversion events, their operational rules differ sharply.
For Meta Conversions API, every event targets a numbered Meta dataset and specifies an action source. Website events (action_source: "website") must include a clean event_source_url and an unhashed browser client_user_agent, plus event_id for browser-to-server deduplication. During testing, requests carry a test event code so operators can watch payloads arrive inside Meta Events Manager's Test events tab.
Warning
WhatsApp conversions add a second critical twist. WhatsApp conversion events use action_source: "business_messaging" with a ctwa_clid click identifier and a 7-day attribution window, and Meta does not deduplicate business_messaging events. Retrying a timed-out HTTP request blindly could double-count a sale inside Meta. The dispatcher therefore records an in-flight stamp right before sending; if the call times out or the process crashes before receiving a response, the row stops for human review instead of retrying automatically.
For Google Ads Data Manager API (v1/events:ingest), Google supports a true dry-run flag: validate-only (validateOnly: true). Google checks authentication, OAuth scopes, schema structure and hash formatting completely without recording any conversion in Google Ads. Because nothing is recorded, a passing validate-only check records a validation diagnostic code and must never be labelled sent. Google also defines a four-part AddressInfo object where first and last names are hashed while country (regionCode) and postal code (postalCode) must be plain text; under owner decision OD-15, this repository stores only hashed e-mail and phone at rest today and emits AddressInfo only when all four fields are valid.
Attribution basics and honest integer KPI math
Attribution decides which ad or channel receives credit for a sale. Suppose a shopper taps an Instagram video on Tuesday, clicks a Google Search ad on Thursday and completes a 2,000 lira order. Meta's 7-day window claims 2,000 lira, and Google's click window also claims 2,000 lira. Neither platform is necessarily lying under its own rules, yet adding their two figures together produces 4,000 lira of imaginary sales when the shop actually collected 2,000 lira.
This repository prevents double-counting by keeping three revenue ledgers strictly apart:
- Finance (store net sales): Real store orders minus refunds, returns and order adjustments.
- First-party attributed: Store orders deterministically matched to recorded first-party click identifiers, where each order counts at most once.
- Vendor attributed: Each ad platform's self-reported figure shown separately for that platform alone, never summed across platforms.
Even with clean ledgers, three mathematical mistakes routinely corrupt marketing dashboards:
- Averaging ratios instead of taking the ratio of sums. Imagine Campaign A spent 100 lira and brought 1,000 lira (ROAS
10.00), while Campaign B spent 9,900 lira and brought 9,900 lira (ROAS1.00). Averaging10.00and1.00gives5.50, whereas total revenue (10,900lira) divided by total spend (10,000lira) is1.09. Every combined rate — ROAS, MER, POAS, CPA, CAC, CPC, CPM and conversion rate — must use ratio of sums: add all numerators, add all denominators, then divide once. - Turning zero denominators or missing costs into zero. If a new campaign has spent
0lira, ROAS has a zero denominator; if a campaign spent5,000lira and won0orders, CPA and customer acquisition cost (CAC) have a zero denominator; if a store has0clicks or0sessions, conversion rate has a zero denominator; if an order line has no recorded product cost (cogs_minor IS NULL), profit margin and POAS are unknown. Under the unknown is not zero invariant (ruleT071), every uncomputable metric is stored asnulland displayed as an em dash (—), never0,0%, not-a-number or infinity. - Using floating-point currency. Adding
0.1 + 0.2in IEEE-754 floating point accumulates penny drift across thousands of daily rows. As taught in Lesson 3, every monetary value is stored in whole integer minor units (kuruş or cents) and aggregated with exactBigIntarithmetic before formatting.
How this repository does it
Single normaliser and edge collector
One shared module, pii-normalization.ts, owns every platform normalisation and SHA-256 hashing rule across the monorepo. Its outputs are locked against official provider examples in pii-provider-vectors.ts, including Meta digit-only phones (phone_sha256_meta), Google E.164 phones (phone_sha256_e164), North American 10-digit numbering completion, Gmail dot and +alias stripping (email_sha256_google), and OD-16 NFC spec-exact plus Turkish-locale and legacy ASCII-folded variants for fn, ln and ct.
When a storefront event hits apps/collector/src/app.ts, the collector executes five guards in sequence:
- Checks allowed origin and endpoint parameters, and drops unusable pre-split phone hash pairs via
d14-phone-guard.ts. - Strips query parameters, fragments and embedded secrets from
event_source_urlviasanitize-url.ts. - Runs
hashPiiBundleusingpii-normalization.tsand discards all raw PII strings. - Verifies zero raw e-mail, phone or IP shapes remain using
assertNoRawPiifromnormalize.ts, then attachesclient_user_agentafter confirming it contains no raw IP address. - Signs the raw JSON body with HMAC-SHA256 and forwards the batch to
POST /v1/ingest/events.
Signed ingest, database deduplication and least-privilege dispatch
At event ingest (ingest-webhooks.ts), the API verifies the raw-body HMAC signature, re-checks for raw PII, evaluates evaluateDestinationConsent per destination (meta_capi, google_dm), and writes rows inside one workspace-scoped PostgreSQL transaction.
PostgreSQL's partitioned tracking_events table cannot hold a global unique constraint that omits its partition timestamp (occurred_at), which meant a delayed replay arriving 48 hours later could slip into a new partition. Migration 0009_tracking_event_keys_and_dispatch_lease.sql solved this by introducing a non-partitioned companion table, tracking_event_keys, keyed uniquely on (workspace_id, destination, event_name, event_id) with ON CONFLICT DO NOTHING. Migration 0012_tracking_events_meta_website_fields.sql added dedicated columns for Meta website fields (event_source_url and transient client_user_agent) plus an index for lease claiming.
Outbound dispatch runs in a separate process, dispatch-main.ts, driving signal-dispatch.ts:
- Least privilege: Only the dispatch process holds permission to lease queued rows and read encrypted platform tokens through the vault executor path.
- Fencing lease: Batches are claimed with a lease duration of at least twice the worst-case dispatch group runtime so two workers cannot send the same batch concurrently.
- Meta CAPI builder (
meta-capi.ts): Targets Graph APIv27.0, sendstest_event_codewheneverDispatchModeistest(the default), requiresDISPATCH_LIVE_ACKNOWLEDGED=owners-signed-off-OD-05to enterlivemode, stampsDISPATCH_IN_FLIGHTbefore WhatsAppbusiness_messagingsends (falling back toMETA_OUTCOME_UNKNOWNon lost outcomes), and clearsclient_user_agentonce a row reaches a final state. - Google Data Manager builder (
google-dm.ts): Targetsv1/events:ingestwithvalidateOnly: truehard-coded in every mode today, recordingGDM_VALIDATE_ONLY_PASSEDorGDM_VALIDATE_ONLY_REJECTEDwithout ever marking a rowsent. - Delivery visibility: Workspace owners inspect per-destination results, diagnostic codes,
provider_trace_idandevents_receivedthrough delivery status (signals-delivery-status.ts) and attribution health insignals-attribution-quality.ts. Changing a workspace's tracking endpoint (signals-tracking-endpoints.ts) requires an owner-approvedTRACKING_UPDATE_DESTINATIONrequest with step-up MFA, covered in Lesson 8.
Pure integer KPI math and unit-economics rollups
All core metric formulas live in layer0-analytics.ts, kpi-ledger.ts and overview-unit-economics-rollup.ts. Each module sums minor-unit BigInt values across the reporting window first, divides once for ratio-of-sums metrics (ROAS, MER, POAS, CPA, CAC, CPC, CPM, CTR and conversion rate), keeps the three revenue ledgers separate, tags freshness (LIVE, PARTIAL, FINAL, STALE, UNKNOWN), and converts any zero denominator or null cogs_minor into null rendered as — by DataMetric.tsx.
Not built yet
What went wrong once
Building the measurement pipeline across Waves 45 through 48 exposed real subtle defects that unit tests and security reviews caught before any live call was ever made.
- Turkish UTF-8 letters were folded away before the primary hash (
OD-16). Early code ranfoldTurkishToAsciion every name and city before SHA-256 hashing, turningŞişliintosisliand silently breaking matches against Meta and Google's UTF-8 customer indexes. Fixing this underOD-16split normalisation so the NFC UTF-8 spec-exact hash is always sent first, with optional Turkish-locale and legacy ASCII-folded hashes appended behind it only when distinct. - Partial Google
AddressInforisked schema rejections and unwanted plaintext storage (OD-15). Early builders could emit an incomplete address object or store plain postal codes that conflicted with strict data minimisation. EnforcingOD-15kept storage restricted to hashed e-mail and phone at rest and madegoogle-dm.tsemitaddressInfoonly when all four fields (hashed given name, hashed family name, plainregionCodeand plainpostalCode) are valid together. - Meta
websiteevents lacked required browser fields, and then the PII scanner blocked user agents. Website CAPI events initially omittedevent_source_urlandclient_user_agent, which Meta rejects onaction_source: "website". After migration0012added both fields,scanForRawPiiimmediately flagged real browser user-agent strings whose version digits resembled phone numbers. The fix sanitisedevent_source_url, attachedclient_user_agentafter the general PII barrier with a dedicated check rejecting embedded IP addresses, and clearedclient_user_agentas soon as dispatch finishes. - Legacy pre-split phone hash pairs leaked past ingest. Some storefront payloads carried separate
phone_country_code_hashandphone_local_hashfields that neither Meta nor Google can match. Addingd14-phone-guard.tsvalidated and dropped those pairs cleanly at the edge collector. - Partitioned tables allowed delayed duplicate events across partition boundaries. Because PostgreSQL requires partition keys inside unique constraints on partitioned tables, a duplicate purchase replayed 48 hours later with a shifted timestamp could land in a newer
tracking_eventspartition and fire a second conversion. Migration0009closed this permanently with the non-partitionedtracking_event_keysside table. - WhatsApp
business_messagingevents had no platform-side deduplication. Treating WhatsApp CAPI retries like website retries risked double-counting chat sales whenever a network timeout hid Meta's HTTP reply. Adding theDISPATCH_IN_FLIGHTstamp turned ambiguous failures intoMETA_OUTCOME_UNKNOWNfor human inspection instead of automatic retries.
Try it yourself
Every step below runs locally without starting a server, touching PostgreSQL or calling Meta or Google. Run these commands from the repository root in PowerShell or Git Bash.
Step 1: Run the official Meta and Google PII provider-vector conformance tests
This proves that the single normaliser matches published Meta and Google SHA-256 test vectors byte for byte, including split phone hashes, Gmail alias stripping and Turkish OD-16 variants.
pnpm --dir packages/shared exec vitest run test/pii-provider-conformance.test.tsConfirm that every conformance test passes with zero skipped cases.
Step 2: Run the core signals consent, deduplication and platform builder suite
This exercises the KVKK and Consent Mode v2 consent gates, non-timestamp deduplication logic, Meta CAPI and Google Data Manager validateOnly builders, and reconciliation rules.
node --test packages/signals/test/signals.test.mjsLook for passing cases verifying that declined consent produces skipped_no_consent with zero outbound payloads and that Meta and Google receive distinct phone digests.
Step 3: Verify Google AddressInfo and Meta name-variant behaviour
This checks the exact OD-15 four-field address guard and the OD-16 hash-array ordering for Turkish names and cities.
node --test packages/signals/test/google-address-and-meta-name-variants.test.tsConfirm that partial address objects are omitted rather than sent incomplete and that spec-exact hashes appear first.
Step 4: Inspect how the edge collector strips URLs and handles client_user_agent
Run the collector forwarding tests to watch URL query stripping, hash-on-ingest and the narrow client_user_agent IP guard in action.
pnpm --dir apps/collector exec vitest run test/meta-website-fields-forwarding.test.tsNotice that query strings are removed from event_source_url while valid browser user-agent strings pass through cleanly and IP-bearing strings are rejected.
Check yourself
0 / 6Why does this repository hash a customer's phone number twice instead of storing one shared phone digest for both Meta and Google?
A visitor clicks Accept on marketing consent, so consent_marketing is true, while Google Consent Mode v2 consent_ad_user_data is "DENIED". What should happen to the event?
Why did migration 0009 add a separate non-partitioned tracking_event_keys table instead of relying only on a unique index inside tracking_events?
A WhatsApp business_messaging purchase event times out after leaving the dispatch process, so no HTTP response from Meta is received. What does the dispatcher do?
Campaign A spent 200 lira and brought 2,000 lira in revenue (ROAS 10.00). Campaign B spent 9,800 lira and brought 9,800 lira (ROAS 1.00). What is the honest combined ROAS?
A shop sold 50 units of a new product for 25,000 lira after spending 5,000 lira on ads, but the owner has not entered the product's cost (cogs_minor is NULL). What should the API and UI report for POAS and contribution margin?
Words to know
32Go deeper
In this repository
- Architecture decisions:
ADR-0002 Dual Server-Side Meta CAPI and Google Data Manager,ADR-0007 KVKK Consent Gate and DB ResidencyandOwner Decisions(OD-05,OD-15,OD-16). - Operator runbook and wave evidence:
Send Meta Test Event Runbook,Wave 47 C ReportandWave 48 A Report. - Companion lessons: Lesson 3 (Data, PostgreSQL and exact money), Lesson 5 (Cryptography, SHA-256 and HMAC) and Lesson 8 (Approvals and safe automation).
- Archived lessons absorbed by this chapter:
Archived lesson 02 (KPI math, CAPI and attribution),Archived lesson 19 (CAPI and attribution drills),Archived lesson 22 (Attribution quality and cross-route fuzzing),Archived lesson 28 (Signal freshness SLA)andArchived lesson 33 (Unit economics and T071).