The shop database as the source of truth: sending purchases from the server

TL;DR

Difficulty: Advanced

Your order table is the truth. The browser tag is a sample of it, missing every purchase lost to blockers, payment detours and closed tabs.

  • Let the shop report purchases itself, from the server: GA4 Measurement Protocol, Meta Conversions API, Google Ads through the Data Manager API.
  • Capture the browser identifiers and the customer's consent at checkout, because the server cannot ask later.
  • Write one outbox row per consented destination when Solidus finalises the order, and let a background job deliver and retry.
  • A hashed email is still personal data. Send it only with advertising consent.
  • Alarm against the database, not against a guess.

Google Analytics shows fewer purchases than your shop, and the ad platforms fewer still. Part of that gap is customers who said no, and it should stay. The rest is technical accident, and your shop can repair it by telling the platforms itself. Here is how to build that properly in Rails and Solidus, from consent at checkout to the alarm that tells you when it stops.

The browser is a sample, the order table is the census

Every online shop has two records of what was sold. One is the order table in the shop's own database: every order, every line, every refund, written by the code that took the money. The other is what the browser managed to report to Google Analytics, Meta and Google Ads, one tag at a time, from a device you do not control.

The question this chapter answers is the one in the title: should the browser or your shop tell analytics and the ad platforms what happened? My answer is both, with a clear order of rank. The order table is the truth. The browser is a sample of it, and a sample with holes in predictable places. When a purchase matters, and every purchase does, the shop itself should tell the platforms, from the server, using the order it has just saved.

This is an advanced chapter, so a few words first. A server event is a message about something that happened (a purchase, a refund) sent by your shop's server directly to a platform's API, rather than by a script in the visitor's browser. An API is the documented door a platform offers for other software to send or read data. Deduplication means making sure a sale that arrives twice, once from the browser and once from the server, is counted once.

If you have not read the purchase event done right, read it first: it settles what goes into a purchase event (value, tax, shipping, currency, items). This chapter is about who sends it, and how to make sure it arrives. The general case for server side tagging, the Google Tag Manager server container and Meta's payload format are covered in server side tracking: the technical guide. I will not repeat that guide. Here the server is not a tag container. It is the shop itself, Ruby on Rails and Solidus, sending events straight from the order.

Example: what Shannonside Home's browser saw in October

Shannonside Home is the invented homeware shop this series follows: ceramics, kitchen textiles, lamps and small furniture, about 1,400 products, sold from Limerick at shannonsidehome.example. Niamh owns it, Callum is the developer. Its baseline month (all numbers invented for the example): 110,000 sessions, a conversion rate of 1.8%, an average order value of €84.

So the order table holds:

110,000×0.018=1,980 orders110{,}000 \times 0.018 = 1{,}980 \text{ orders}

and 1,980×84=166,3201{,}980 \times 84 = 166{,}320, so €166,320 of revenue.

In October, 64% of buying customers (1,267 of the 1,980) had accepted analytics cookies, and 55% (1,089) had accepted advertising cookies. These rates are the example's, not a benchmark. GA4, fed only by the browser tag, recorded 1,052 purchases. Meta's pixel recorded 893.

To compare these, Callum uses one ratio, the coverage of a destination: the share of real orders that the destination actually received. It is a plain ratio, explained in Foundations: ratios and rates.

cd=EdOc_d = \frac{E_d}{O}

where cdc_d is the coverage of destination dd, EdE_d is the number of purchase events destination dd received in the period, and OO is the number of orders in the shop's database in the same period.

For GA4 in October:

cGA4=1,0521,980=0.531c_{\text{GA4}} = \frac{1{,}052}{1{,}980} = 0.531

So GA4 saw 53.1% of the orders. For Meta, 893/1,980=0.451893 / 1{,}980 = 0.451, so 45.1%. Neither number is wrong in itself. Each is a sample. The next section takes it apart.

What the browser loses, and what no server can get back

The browser loses purchases for two very different kinds of reason, and it pays to keep them apart, because a server fixes one kind and must never touch the other.

Losses the customer chose. A customer who declined analytics or advertising cookies said no. That choice belongs to them, and a server is not a way around it. Consent is covered in depth in cookies, consent and the ePrivacy mess and in event tracking and consent mode. In this chapter the rule is simple: the server sends for a customer only what the customer agreed to.

Losses the customer never chose. These are technical accidents, and the customer did not ask for any of them:

  • Blockers. A browser extension or a privacy setting stops the tag's script from loading, even though the customer clicked "accept" on your banner.
  • The payment detour. The customer pays on PayPal's page, or completes a bank check for their card, and the confirmation page in your shop never loads on their device. The order exists, the "thank you" page never fired a tag.
  • The tab that closed too early. The confirmation page loads, the customer closes the tab or loses signal before the tag has sent its request.
  • Shortened cookies. Safari's Intelligent Tracking Prevention deletes cookies and other storage created by scripts after seven days without the visitor interacting with the site, and caps such cookies at 24 hours when the visitor arrives through a link with click identifiers in it1. A customer who clicks an ad on Monday and buys the following Wednesday may arrive with a fresh, unknown analytics identity.

A server event fixes the second group, as long as the customer consented. It sends from the shop, after the order is saved, so it does not care whether the confirmation page loaded or whether a script was blocked. It cannot and must not fix the first group.

Example: where Shannonside's 928 missing GA4 purchases went

Callum matches GA4's purchases to orders by order number (the transaction ID) and sorts every order GA4 never saw into one of four buckets:

ReasonOrdersCan a server send it?
No analytics consent713No, and it must not
Script blocked despite consent92Yes
PayPal return page never loaded71Yes
Tab closed before the tag fired52Yes
Total missing928215 of them

The arithmetic: 1,980−1,267=7131{,}980 - 1{,}267 = 713 orders without analytics consent. Of the 1,267 consented orders, GA4 received 1,052, so 1,267−1,052=2151{,}267 - 1{,}052 = 215 were lost by accident, and 92+71+52=21592 + 71 + 52 = 215 confirms the split.

Example figures. The shop recorded 1,980 orders. 713 customers declined analytics, leaving 1,267 consented orders. The browser tag then lost 92 to blockers, 71 to PayPal returns that never loaded and 52 to tabs closed early, so GA4 received 1,052 purchases. A server event recovers the 215 accidental losses but not the 713 refusals. Tap or click to open full screen and move around

With a server event, GA4 would receive all 1,267 consented purchases: coverage 1,267/1,980=0.6401{,}267 / 1{,}980 = 0.640, so 64.0% instead of 53.1%. The ceiling is the consent rate, not 100%, and that is how it should be. The other 713 orders are still in Niamh's own reports, because her reports for money come from the database, not from GA4. Which system answers which question is the subject of when analytics, ads and orders disagree.

Three destinations, three APIs, three sets of rules

A shop like Shannonside usually sends purchases to three places: GA4 for behaviour, Meta for its ads, Google Ads for its ads. Each has its own server API, and they differ in exactly the details that break a naive build: which identifier ties the event to a visitor, how late an event may arrive, and which field removes duplicates.

GA4 Measurement ProtocolMeta Conversions APIGoogle Ads via the Data Manager API
What ties it to a visitorclient_id from the GA4 taghashed email or phone, plus browser details such as fbp, fbc and the user agentthe Google click ID (gclid), optionally hashed email
How late it may arrivebackdated up to 72 hours, within 48 hours to join browser eventsevent_time up to 7 days old, ideally within an hourafter the click, inside the conversion action's click through window
Duplicate keytransaction_idevent_id plus event_nametransactionId per conversion action
Consent fieldconsent.ad_user_data, consent.ad_personalizationnone in the payload, you filter before sendingconsent.adUserData, consent.adPersonalization
Says if it failedno, always answers 2xxyes, rejects the requestyes, with diagnostics retrieved later

The sources for every cell are in the three subsections below.

GA4 takes server events through the Measurement Protocol

The Measurement Protocol is GA4's API for events sent server to server. Google is explicit about its role: it is meant to augment the collection through the GA4 tag or Tag Manager, not to replace it, and with the Measurement Protocol alone only partial reporting may be available2. So the GA4 tag keeps running in the browser for page views and the shopping journey. The server adds the purchase that matters most.

For a website, each request goes to https://www.google-analytics.com/mp/collect with two values in the address: the measurement_id of the data stream and an api_secret you create in the GA4 interface. The body must contain a client_id, and Google says it should match the ID generated by the GA4 tag on your website3. That one line decides the whole design: the server can only attach a purchase to the right visitor if the shop saved the visitor's client_id before the order completed.

The other rules from Google's reference4:

  • Up to 25 events per request, up to 25 parameters per event, a body under 130 kB.
  • Events may be backdated up to 72 hours with timestamp_micros. To be joined with events from the GA4 tag, they should arrive within 48 hours of the original browser event3.
  • A consent object carries ad_user_data and ad_personalization, each GRANTED or DENIED.
  • Include session_id and engagement_time_msec, or the event does not count properly in engagement metrics. To tie the event to the visitor's session (and so to the campaign that brought them), send the session_id within 24 hours of the session's start2.
  • The Measurement Protocol does not return an error code if the payload is malformed or the data is not processed. It answers with a 2xx status as soon as the request is received4.

That last rule matters more than it looks. A server that relies on the response to know whether GA4 accepted the event will believe everything worked, forever. There is a separate validation server at /debug/mp/collect, which returns validationMessages and never shows events in reports5. It belongs in your tests, not in production.

Meta: the Conversions API

Meta's Conversions API takes events at https://graph.facebook.com/{API_VERSION}/{PIXEL_ID}/events, with an access token as a parameter, up to 1,000 events in one request. An event's event_time may be up to seven days before the request, and if any event in the batch is older, the whole request fails and none of it is processed. Meta recommends sending events as soon as they occur, ideally within an hour6.

For a purchase made on your website, three fields are easy to miss. action_source is required and is website. event_source_url is required for website events. And client_user_agent, the browser's identification string, is required for website events too78. Contact details such as email and phone must be normalised and hashed with SHA256, while the IP address, user agent and the fbp and fbc browser identifiers are sent unhashed8. The shape of the full payload is in the server side tracking guide, so I will not repeat it.

The same lesson as GA4: the user agent, fbp and fbc exist only in the browser. The server can send them only if the shop saved them while the customer was still there.

Google Ads can learn about a purchase in three ways: its own tag in the browser, a GA4 key event imported into Google Ads, or an upload from your server. The server route matters here.

Google has moved this route to a new API. Its Google Ads API documentation now says that from 15 June 2026, new implementations of offline conversions and enhanced conversions for leads must use the Data Manager API instead9. So a shop building this today builds it there. A request goes to https://datamanager.googleapis.com/v1/events:ingest with the OAuth scope https://www.googleapis.com/auth/datamanager10. Each event carries a transactionId, an eventTimestamp, a conversionValue and currency, the click identifier under adIdentifiers.gclid, optional hashed contact details under userData, and a consent object with adUserData and adPersonalization. Within one conversion action, Google Ads uses transactionId to deduplicate: the first event received counts, and later events with the same ID are treated as adjustments11. Setting validateOnly to true checks a request without recording anything11.

Two timing notes from Google Ads Help: conversions imported within one day of the click may not be recorded yet, and Google recommends including an extra day of data in each import12. In practice that means uploading the previous day's orders once a day, overlapping by a day, and letting transactionId remove the overlap.

Example: what order R482913 needs for each destination

On a Tuesday evening in October, a customer orders a stoneware jug and two linen tea towels from Shannonside, €84 in total. She arrived from a Google Shopping ad, accepted all cookies, and paid by PayPal. Order number R482913.

DestinationWhat the server must have savedWhere it came from
GA4client_id 1872623561.1792850400, session_id 1792850400read from the GA4 tag on the checkout page
Metauser agent, fbp, email (hashed when sending)request headers, the _fbp cookie, the order
Google Adsgclid from the ad clickread from the Google tag on the checkout page
All threethe consent state at checkout: analytics yes, advertising yesthe consent banner's record

The PayPal return page never loads on her phone. The browser sends nothing. Because the shop saved these values at the confirmation step, before she left for PayPal, the server sends all three events a few seconds after the order completes. Without them, the server would know the order and not the visitor, and GA4 and Google Ads could not credit the ad that brought her.

Capture the context at checkout, because the server cannot ask later

The previous example shows the design rule this whole chapter rests on: anything that only the browser knows must be copied into the shop's database while the customer is still on the page. After the order completes, the browser may be gone.

What to capture, at the last checkout step, and only when the matching consent exists:

  • Analytics consent: the GA4 client_id and session_id. The GA4 tag hands both over through its get command13.
  • Advertising consent: the gclid (also available through get13), the _fbp and _fbc cookies, the user agent, and the IP address if you choose to send it.
  • Always: which consent the customer gave, in which version of your banner, and when.

Callum stores these in a table of their own, one row per order, rather than adding columns to Solidus's spree_orders table. That keeps tracking data apart from the order, so it can be deleted on its own schedule.

Example: Callum's migration and the checkout snippet

The table:

# db/migrate/20261020090000_create_order_tracking_contexts.rb
class CreateOrderTrackingContexts < ActiveRecord::Migration[8.0]
  def change
    create_table :order_tracking_contexts do |t|
      t.references :order, null: false, index: { unique: true },
                           foreign_key: { to_table: :spree_orders }
      t.boolean :analytics_consent, null: false, default: false
      t.boolean :ads_consent, null: false, default: false
      t.string  :consent_version
      t.datetime :consent_recorded_at
      t.string  :ga_client_id
      t.bigint  :ga_session_id
      t.string  :gclid
      t.string  :fbp
      t.string  :fbc
      t.string  :user_agent
      t.timestamps
    end
  end
end

On the confirmation step, a few lines of JavaScript copy what the tags know into hidden form fields. The get command only answers if the GA4 tag is running, and on Shannonside's site it only runs after consent, so for a customer who declined, the fields simply stay empty.

// app/javascript/checkout_context.js
const form = document.querySelector('#checkout_form_confirm')
const put = (name, value) => {
  const field = form?.querySelector(`input[name="tracking[${name}]"]`)
  if (field && value) field.value = value
}

if (form && typeof gtag === 'function') {
  gtag('get', 'G-SHANNON01', 'client_id', (id) => put('ga_client_id', id))
  gtag('get', 'G-SHANNON01', 'session_id', (id) => put('ga_session_id', id))
  gtag('get', 'AW-123456789', 'gclid', (id) => put('gclid', id))
}

The checkout controller saves the row when the customer confirms. In the Solidus starter frontend, that is the update action of CheckoutsController. The consent comes from the shop's own record of the banner choice, never from the form, because a form field can be edited by anyone.

# app/controllers/concerns/captures_tracking_context.rb
module CapturesTrackingContext
  extend ActiveSupport::Concern

  included do
    before_action :capture_tracking_context, only: :update, if: -> { @order&.confirm? }
  end

  private

  def capture_tracking_context
    consent = ConsentRecord.current_for(cookies)   # the banner's stored choice
    fields  = params.fetch(:tracking, {}).permit(:ga_client_id, :ga_session_id, :gclid)

    context = OrderTrackingContext.find_or_initialize_by(order: @order)
    context.assign_attributes(
      analytics_consent: consent.analytics?,
      ads_consent: consent.ads?,
      consent_version: consent.version,
      consent_recorded_at: consent.recorded_at,
      ga_client_id: (fields[:ga_client_id] if consent.analytics?),
      ga_session_id: (fields[:ga_session_id] if consent.analytics?),
      gclid: (fields[:gclid] if consent.ads?),
      fbp: (cookies[:_fbp] if consent.ads?),
      fbc: (cookies[:_fbc] if consent.ads?),
      user_agent: (request.user_agent if consent.ads?)
    )
    context.save!
  end
end

ConsentRecord stands for whatever your consent banner stores. Every value is saved only under the consent that covers it, so the table never holds an identifier the customer did not agree to.

A server event is sent seconds, hours or a day after the click on the banner. By then, the banner is not there to ask. So the consent the customer gave at checkout must travel with the order, and the sending code must read it from the order, every time.

This is not only good engineering. The GDPR requires that where processing is based on consent, the controller must be able to demonstrate that the person consented14. A row that says "analytics yes, advertising yes, banner version 2026.3, 20 October 2026 at 7.14pm", stored next to the order, is that demonstration.

What each destination needs, in plain words:

  • The browser identifiers themselves. Reading the _ga, _fbp or _fbc cookies means accessing information stored on the customer's device. In Ireland that falls under regulation 5 of S.I. No. 336 of 2011, the ePrivacy Regulations: storing or accessing such information needs the person's consent, unless it is strictly necessary for a service they asked for15. Analytics and advertising are not strictly necessary, so both kinds of identifier need consent. The detail, and how the Data Protection Commission reads it, is in the consent article.
  • Google's own rule. Google's EU user consent policy requires consent for end users in the European Economic Area, the UK and Switzerland, both for cookies where legally required and for the collection, sharing and use of personal data for ad personalisation16. The consent fields in the Measurement Protocol and the Data Manager API are how the server passes that answer on.
  • Meta's own rule. Meta's Business Tools Terms require that you have a lawful basis for sharing the data, give a prominent notice, and obtain, in a verifiable manner, any consent the law requires before Meta cookies are enabled17. The Conversions API payload has no consent field, so the filter is your code: no advertising consent, no Meta event.

This is general information, not legal advice. Your privacy notice must also say that you send purchase data to these platforms from your server, because a customer who reads it should not be surprised.

Example: three Shannonside customers, three different answers

CustomerConsent at checkoutGA4MetaGoogle Ads
Aanalytics yes, ads yespurchase with client_id, consent grantedpurchase with hashed email, fbp, user agentclick conversion with gclid
Banalytics yes, ads nopurchase with client_id, ad_user_data and ad_personalization deniednothingnothing
Canalytics no, ads nonothingnothingnothing

Customer C's order is still a full order in the database, with revenue, margin and products. It appears in every report Niamh runs from her own data. It is simply never sent to anyone else.

Hashing is pseudonymisation, not anonymisation

Meta and Google ask for email addresses and phone numbers as SHA256 hashes. A hash is a one way fingerprint: the same input always gives the same 64 character output, and you cannot run the function backwards. It is easy to conclude that a hashed email is anonymous. It is not.

The European Data Protection Board says it directly: pseudonymised data that could be attributed to a person by using additional information remains information about an identifiable person, and so remains personal data18. The same guidelines give the exact case: if you know the transformation is merely a SHA256 hash of a name, you can hash all the names you hold elsewhere and see which hashes match18.

That is precisely how ad platforms use a hashed email. They hash the email addresses of their own users the same way and look for matches. The match is the purpose. So a hashed email sent to Meta or Google is personal data, sent for advertising, and needs the lawful basis and consent of the previous section. Hashing is still required (Meta's terms make you hash contact information to its specification before sending17), because it keeps raw addresses out of logs and transit. It is a safety measure, not a pass.

Example: Customer A's email, before and after

Customer A typed her email as Aoife.Brennan@Mail.example with stray spaces and capitals. Meta's normalisation is: trim the spaces, lower case everything, then hash8.

require "digest"

email = "  Aoife.Brennan@Mail.example ".strip.downcase
# => "aoife.brennan@mail.example"
Digest::SHA256.hexdigest(email)
# => "68ac43c423b38d6ad9c734b663e32f1c79d072d9c9712a698e3f34b6e4c3920b"

Now the test the EDPB describes. Anyone who has the address aoife.brennan@mail.example on a list of their own can hash it and get the same 64 characters, and so knows that this purchase was hers. Meta, with over a billion addresses, does exactly that. Callum therefore treats the hash like the address: sent only with advertising consent, never logged in full, and kept out of the outbox payload until the moment of sending (more on that below).

One ID, generated once, removes the duplicates

When the browser tag and the server both send a purchase, each platform receives it twice. Each has its own way of recognising the pair, and all three rely on the same thing: one ID for the sale, generated once, used by both senders.

  • GA4 deduplicates purchase events with the same transaction_id. Google warns never to send an empty string (every such purchase would collapse into one) and never to reuse an ID across different orders19.
  • Meta matches the pixel's eventID to the server's event_id together with the event name, and only within 48 hours of receiving the first event with that ID20.
  • Google Ads keeps the first event per transactionId within a conversion action11.

The order number is the natural ID: unique, known to the confirmation page and to the server. The server side tracking guide works through Meta's case in numbers. What this chapter adds is the server side discipline: the outbox row for each destination carries the order number as its key, and a unique index in the database makes it impossible to queue the same sale twice for the same place.

Example: order R482913 arrives three times

Customer A's PayPal return page does load on her phone the next morning, when she reopens the browser, and the GA4 tag fires a purchase for R482913 about 14 hours after the server already sent it. Meanwhile, Callum's first build had a bug that queued the server event twice.

ArrivalSenderIDCounted by GA4?
1server, 7.15pmtransaction_id R482913yes
2server again, 7.15pm (the bug)R482913no, duplicate
3browser, 9.02am next dayR482913no, duplicate

GA4 counts one purchase. For Meta, the browser event arrives 13 hours 47 minutes after the server's, well inside the 48 hours, so it is dropped as well. Had the confirmation page fired with a random ID instead of the order number, Meta would have counted two purchases and Niamh's return on ad spend would have looked better than it was. Callum fixes the queueing bug anyway, with the unique index in the next section, because relying on every platform's deduplication is relying on three different sets of rules you do not control.

The outbox: write the promise next to the order

Here is the trap in the obvious build. The order completes, and in the same request the code calls three APIs. If Meta is slow, the customer waits. If Google is down, the event is lost. If the server restarts between saving the order and calling GA4, the event is lost and nobody knows.

The transactional outbox pattern solves this. Instead of sending the message straight away, the code first stores the message in the database, next to the business data, and a separate process sends stored messages later21. The order and the promise to report it are saved together. If the sending fails, the promise is still there, and the sender tries again. Chris Richardson, who documented the pattern, adds the consequence: the relay may publish a message more than once, so the receiver must cope with duplicates21. Your receivers already do, through the IDs of the previous section.

Solidus gives a clean place to write the outbox rows. It has an event bus, Spree::Bus, and when an order completes, Spree::Order#finalize saves the order, sets completed_at, and then publishes :order_finalized with the order in the payload2223. A subscriber listens for that event. The Solidus guides add a warning that shapes the design: the main flow should not wait for subscribers before completing24. So the subscriber does one fast thing, writing rows, and never calls an outside API.

Tap or click to open full screen and move around

Example: Callum's outbox table, model and subscriber

The table holds one row per order, destination and event:

# db/migrate/20261020091000_create_tracking_outbox_events.rb
class CreateTrackingOutboxEvents < ActiveRecord::Migration[8.0]
  def change
    create_table :tracking_outbox_events do |t|
      t.references :order, null: false, foreign_key: { to_table: :spree_orders }
      t.string   :destination, null: false   # "ga4", "meta", "google_ads"
      t.string   :event_name,  null: false   # "purchase", "refund"
      t.string   :dedup_key,   null: false   # the order number, or "R482913.refund.1"
      t.string   :status,      null: false, default: "pending"
      t.integer  :attempts,    null: false, default: 0
      t.text     :last_error
      t.datetime :sent_at
      t.timestamps
    end
    add_index :tracking_outbox_events, %i[destination event_name dedup_key],
              unique: true, name: "index_outbox_once_per_destination"
    add_index :tracking_outbox_events, %i[status created_at]
  end
end

Notice what the row does not hold: no email, no hash, no payload. It is a promise ("send the purchase for R482913 to Meta"), and the job builds the payload from the order and its context at the moment of sending. That keeps personal data out of a second table, and means a correction to the order (say, a fixed tax line) is picked up automatically if the row is still pending.

The model, with the consent rule in one place:

# app/models/tracking_outbox_event.rb
class TrackingOutboxEvent < ApplicationRecord
  belongs_to :order, class_name: "Spree::Order"

  DESTINATIONS = {
    "ga4"        => ->(ctx) { ctx.analytics_consent && ctx.ga_client_id.present? },
    "meta"       => ->(ctx) { ctx.ads_consent && ctx.user_agent.present? },
    "google_ads" => ->(ctx) { ctx.ads_consent && ctx.gclid.present? }
  }.freeze

  scope :pending, -> { where(status: "pending") }

  def self.enqueue_for(order, event_name:, dedup_key: order.number)
    context = OrderTrackingContext.find_by(order: order)
    return [] unless context

    DESTINATIONS.filter_map do |destination, allowed|
      next unless allowed.call(context)
      create_or_find_by!(order: order, destination: destination,
                         event_name: event_name, dedup_key: dedup_key)
    end
  end
end

create_or_find_by! relies on the unique index: if the row already exists, it returns the existing one instead of adding a second. That is the fix for the double queueing bug in the previous example.

The subscriber, following the Solidus guide's structure:

# app/subscribers/shannonside/tracking_subscriber.rb
module Shannonside
  class TrackingSubscriber
    include Omnes::Subscriber

    handle :order_finalized, with: :queue_purchase, id: :shannonside_queue_purchase

    def queue_purchase(event)
      order = event.payload[:order]
      TrackingOutboxEvent.enqueue_for(order, event_name: "purchase")
      DeliverTrackingEventsJob.perform_later(order.id)
    end
  end
end

# config/initializers/omnes.rb
Rails.application.config.to_prepare do
  Shannonside::TrackingSubscriber.new.subscribe_to(Spree::Bus)
end

For Customer A, the subscriber writes three rows (GA4, Meta, Google Ads) in a few milliseconds. For Customer B, one row (GA4). For Customer C, none. The job that follows does the slow work, outside the customer's request.

A background job that delivers, retries and gives up honestly

The rows are promises. A background job keeps them. Rails 8 ships with Solid Queue as its default Active Job backend, a queue that lives in the database25, so a shop on Rails 8 needs no extra server for this. Sidekiq with Redis works the same way if the shop already runs it.

Three rules for the job:

  • Retry what is temporary. A timeout or a 5xx answer from the platform usually passes. Active Job's retry_on with wait: :polynomially_longer waits about n4+2n^4 + 2 seconds before attempt n+1n + 1, plus a small random extra so that many failed jobs do not all return at the same moment26.
  • Do not retry what is permanent. A 400 answer means the payload is wrong. Sending it again will not help. Mark the row failed and alert.
  • Stop before the platform's deadline. An event that would arrive too late is worse than useless at Meta: one event older than seven days fails the whole batch6.

Example: the job that sends Shannonside's purchases to GA4

# app/jobs/deliver_tracking_events_job.rb
class DeliverTrackingEventsJob < ApplicationJob
  class TemporaryFailure < StandardError; end

  queue_as :tracking
  retry_on TemporaryFailure, Net::OpenTimeout, Net::ReadTimeout,
           wait: :polynomially_longer, attempts: 10 do |job, error|
    TrackingOutboxEvent.pending.where(order_id: job.arguments.first)
                       .update_all(status: "failed", last_error: error.message)
    TrackingAlerts.notify("tracking delivery gave up for order #{job.arguments.first}")
  end

  def perform(order_id)
    TrackingOutboxEvent.pending.where(order_id: order_id).find_each do |row|
      row.increment!(:attempts)
      Senders.for(row.destination).deliver(row)   # raises TemporaryFailure on 5xx
      row.update!(status: "sent", sent_at: Time.current)
    rescue Senders::PermanentFailure => e
      row.update!(status: "failed", last_error: e.message)
    end
  end
end

And the GA4 sender, built on Google's reference34:

# app/services/senders/ga4.rb
require "net/http"

module Senders
  class Ga4
    ENDPOINT = "https://www.google-analytics.com/mp/collect"

    def deliver(row)
      order = row.order
      ctx   = OrderTrackingContext.find_by!(order: order)
      uri   = URI("#{ENDPOINT}?measurement_id=#{ENV.fetch('GA4_MEASUREMENT_ID')}" \
                  "&api_secret=#{ENV.fetch('GA4_API_SECRET')}")

      body = {
        client_id: ctx.ga_client_id,
        timestamp_micros: (order.completed_at.to_r * 1_000_000).to_i,
        consent: {
          ad_user_data: ctx.ads_consent ? "GRANTED" : "DENIED",
          ad_personalization: ctx.ads_consent ? "GRANTED" : "DENIED"
        },
        events: [{
          name: "purchase",
          params: {
            transaction_id: order.number,
            value: TrackingValue.net_revenue(order).to_f,   # the definition from chapter 2
            currency: order.currency,
            session_id: ctx.ga_session_id,
            engagement_time_msec: 1,
            items: order.line_items.map { |li|
              { item_id: li.sku, item_name: li.name, price: li.price.to_f, quantity: li.quantity }
            }
          }
        }]
      }

      response = Net::HTTP.post(uri, body.to_json, "Content-Type" => "application/json")
      raise DeliverTrackingEventsJob::TemporaryFailure, "GA4 #{response.code}" if response.code.start_with?("5")
    end
  end
end

TrackingValue.net_revenue is deliberately one method, used by every sender, so GA4, Meta and Google Ads receive the same value for the same order. Which value that is (with or without VAT and shipping) is decided once, in the purchase event chapter. If you report profit instead of revenue to the ad platforms, the same method is where that decision lives, and ROAS, POAS and MER explains when that is worth doing.

Now the retry timetable. With ten attempts, the job retries nine times. Ignoring the random extra, the waits are:

RetryWait before it (n4+2n^4 + 2 seconds)Time since the first attempt
13 s3 s
218 s21 s
383 s1 min 44 s
4258 s6 min 2 s
5627 s16 min 29 s
61,298 s38 min 7 s
72,403 s1 h 18 min 10 s
84,098 s2 h 26 min 28 s
96,563 s4 h 15 min 51 s

The total is 1+16+81+256+625+1,296+2,401+4,096+6,561=15,3331 + 16 + 81 + 256 + 625 + 1{,}296 + 2{,}401 + 4{,}096 + 6{,}561 = 15{,}333 seconds from the n4n^4 part, plus 9×2=189 \times 2 = 18, so 15,351 seconds, about 4 hours 16 minutes. That fits comfortably inside GA4's 48 hour joining window and Meta's seven days. An outage longer than four hours is not the job's problem any more. It is the sweeper's.

The sweeper: the database checks its own promises

A subscriber can fail to run (a deploy at the wrong second, a bug in a new line of code). A job can give up. So once a night, a second job asks the database two questions that only the database can answer:

  1. Which orders completed in the last three days have a tracking context but no outbox rows?
  2. Which rows are still pending after an hour, or failed?

Solid Queue runs recurring jobs from config/recurring.yml25. The sweeper queues again what is missing and sends again what is stuck, as long as each platform's deadline allows it, and it reports the counts every morning.

Example: the Tuesday Shannonside's subscriber did not run

On Tuesday 10 November, Callum deploys a change at 2.40pm, and for 26 minutes a typo stops the subscriber loading. Orders complete normally (the subscriber is not in the main flow), but 19 orders get no outbox rows.

# app/jobs/tracking_sweeper_job.rb
class TrackingSweeperJob < ApplicationJob
  def perform
    missing = Spree::Order.complete
                          .where(completed_at: 3.days.ago..1.hour.ago)
                          .joins("JOIN order_tracking_contexts c ON c.order_id = spree_orders.id")
                          .where.missing(:tracking_outbox_events)
    missing.find_each do |order|
      TrackingOutboxEvent.enqueue_for(order, event_name: "purchase")
      DeliverTrackingEventsJob.perform_later(order.id)
    end
    TrackingAlerts.daily_summary(requeued: missing.size)
  end
end
# config/recurring.yml
production:
  tracking_sweeper:
    class: TrackingSweeperJob
    schedule: every day at 3am

where.missing needs the association has_many :tracking_outbox_events on the order, which Callum adds with a small decorator. At 3am on Wednesday, the sweeper finds the 19 orders, writes their rows and sends them. The events arrive about 12 hours late, inside GA4's 48 hour window and Meta's seven days. The morning summary says "19 queued again", and Callum knows exactly which deploy caused it. Without the sweeper, those 19 sales would have vanished from the platforms, and nobody would ever have known.

Refunds come from the server too

The browser never sees a refund. The customer is long gone when Niamh refunds a cracked bowl. So refunds are server events by nature, and the same outbox carries them.

Solidus publishes :reimbursement_reimbursed when a reimbursement succeeds, and :order_canceled when an order is cancelled, on the same bus23. A second handler in the subscriber writes rows with event_name: "refund" and a dedup key that includes the reimbursement, so two partial refunds on one order stay two events. GA4 takes a refund event with the original transaction_id and, for a partial refund, the items and value refunded. Google Ads treats a later event with the same transactionId as an adjustment of the original11. The field by field rules for refunds are in the purchase event chapter.

Example: a partial refund on order R482913

Customer A's jug arrives chipped. Niamh refunds the jug, €42 of the €84 order, on 26 October. Solidus records reimbursement 3,071 and publishes :reimbursement_reimbursed. The subscriber writes one row: destination ga4, event refund, dedup key R482913.refund.3071. The job sends a GA4 refund event with transaction_id R482913, the jug as the only item and the refunded value on the same net definition as the purchase. GA4's revenue for the order drops by exactly the jug's share, and so does the revenue in Niamh's database. The two now agree, because they were fed from the same record.

Monitoring: know within hours when events stop

Server events fail quietly. The GA4 endpoint answers 2xx even when it discards your data4. A Meta access token can be revoked by someone tidying up the business account. A Google OAuth credential expires. In each case the shop keeps selling, and the platforms slowly starve.

The database makes monitoring simple, because it knows exactly how many events should have arrived. Three numbers, checked every hour:

  • Outbox lag: pending rows older than 30 minutes. On a healthy day this is zero.
  • Failed rows: any row marked failed in the last 24 hours.
  • Daily coverage per destination: sent rows divided by completed orders, the cdc_d from the start of this chapter, against its usual level.

What not to do is the most common alarm of all: "no purchase in GA4 in the last hour". At night it cries wolf. If orders arrive at random at an average rate λ\lambda per hour, the number in an hour follows a Poisson distribution, explained in Foundations: distributions, and the chance of an hour with none is:

P(N=0)=e−λP(N = 0) = e^{-\lambda}

where P(N=0)P(N = 0) is the probability that an hour has zero orders, NN is the number of orders in that hour, ee is Euler's number (about 2.718), and λ\lambda is the expected number of orders in the hour.

Example: why Shannonside's night alarm kept firing

Shannonside takes 1,980/30=661{,}980 / 30 = 66 orders a day on average, so 66/24=2.7566 / 24 = 2.75 an hour. But not evenly. Between 1am and 6am, the rate is about 0.4 an hour.

At 2am, with λ=0.4\lambda = 0.4:

P(N=0)=e−0.4=0.670P(N = 0) = e^{-0.4} = 0.670

So two nights in three, the 2am hour has no orders at all, and the "no purchase in the last hour" alarm fires on a perfectly healthy system. Even at the daily average, e−2.75=0.064e^{-2.75} = 0.064, it fires falsely about once every 16 hours. After a week of that, nobody reads the alarm, and the real outage goes unnoticed.

For a false alarm rate of at most 1%, the window must be long enough that e−λ≤0.01e^{-\lambda} \le 0.01, so λ≥ln⁡(100)=4.6\lambda \ge \ln(100) = 4.6 expected orders. At night that is 4.6/0.4=11.54.6 / 0.4 = 11.5 hours, far too slow. The better answer is not to guess at all. Callum's alarm compares with the database: "consented orders in the last two hours at least five, and sent Meta rows zero". That cannot fire when the shop is quiet, and it fires within two hours of a real failure.

That is exactly what happened in November. Someone removed the system user behind Meta's access token while tidying the business account. From the next day, every Meta row failed with a permission error.

Example figures. Share of all completed orders delivered by the server to GA4 and to Meta, per day, over 14 days. GA4 holds steady between 63% and 65%. Meta holds between 54% and 56% until day 9, when the access token is revoked and coverage drops to 0%. The alarm fires that morning, the token is replaced, and the sweeper resends the missed events, so day 10 shows 0% and day 11 returns to 55%. Tap or click to open full screen and move around

The alarm fires at 9.40am on day 9, after two hours with 11 consented orders and no Meta event sent. Callum creates a new token, the sweeper sends the failed rows again from day 9 and the morning of day 10, all inside Meta's seven days, and Meta's reporting fills in. Without monitoring against the database, the first sign would have been Niamh asking, a week later, why Meta's campaigns had suddenly stopped selling.

Test it before anyone trusts it

Every piece above can be tested without a single real event leaving the building, and it should be: I work test first, and tracking code is code. Three layers:

  • Unit tests for the rules. Given a context with analytics consent but no ads consent, enqueue_for writes exactly one GA4 row. Given a duplicate call, still one row.
  • Payload tests against the platforms' own validators. GA4's validation server at /debug/mp/collect returns validationMessages, empty when the event is valid5. Meta accepts a test_event_code that sends events to its Test Events view, to be removed in production6. The Data Manager API takes validateOnly11.
  • A system test of the whole path. Complete a checkout in a browser test, then assert the rows exist and the job sends the right body to a stubbed endpoint.
# spec/models/tracking_outbox_event_spec.rb
require "rails_helper"

RSpec.describe TrackingOutboxEvent do
  let(:order) { create(:completed_order_with_totals) }

  it "queues GA4 only when the customer accepted analytics but not ads" do
    OrderTrackingContext.create!(order: order, analytics_consent: true,
                                 ads_consent: false, ga_client_id: "1872623561.1792850400")

    rows = described_class.enqueue_for(order, event_name: "purchase")

    expect(rows.map(&:destination)).to eq(["ga4"])
  end

  it "never queues the same purchase twice for one destination" do
    OrderTrackingContext.create!(order: order, analytics_consent: true,
                                 ads_consent: true, ga_client_id: "1872623561.1792850400",
                                 gclid: "EAIaIQobChMI", user_agent: "Mozilla/5.0")

    2.times { described_class.enqueue_for(order, event_name: "purchase") }

    expect(described_class.where(order: order).count).to eq(3)
  end
end

create(:completed_order_with_totals) is one of the factories Solidus ships for tests. The second test is the one that would have caught the double queueing bug before it ever reached production. Each release then goes through the same test gate as the rest of the shop.

What to build first, at a shop this size

For a shop with Shannonside's numbers, the whole build is a few days of work. Is it worth it at this size? It is. The order matters more than the speed:

  1. Capture the context and consent at checkout. Without it, nothing else works. Do this first, even before any sender exists, so you collect the identifiers from day one.
  2. Outbox table, subscriber and the GA4 sender. GA4 is the easiest API and the one where coverage shows up first.
  3. Meta Conversions API, with deduplication against the pixel. Check in Meta's Test Events view that pairs are recognised.
  4. Google Ads through the Data Manager API, as a daily upload with a one day overlap.
  5. Refunds through the same outbox.
  6. The sweeper and the three alarms. Do not call it finished until an alarm has fired in a test.

Example: Shannonside, before and after

DestinationBrowser only, coverage of ordersBrowser plus server, coverage of ordersCeiling (consent rate)
GA453.1%64.0%64.0%
Meta45.1%55.0%55.0%

For Meta: the pixel received 893 of the 1,089 orders with advertising consent, 893/1,980=0.451893 / 1{,}980 = 0.451. With the server, all 1,089 arrive, 1,089/1,980=0.5501{,}089 / 1{,}980 = 0.550. Both destinations now sit at their ceiling, which is set by the customers' choices and nothing else.

Example figures. GA4 coverage rises from 53.1% with the browser tag alone to 64.0% with server events, which equals the analytics consent rate. Meta coverage rises from 45.1% to 55.0%, which equals the advertising consent rate. The remaining orders are customers who declined, and they stay in the shop's own reports. Tap or click to open full screen and move around

Notice what did not change: the 713 customers who declined analytics. The ad platforms now learn from every sale they are allowed to learn from, and from nothing more. That is also why this is easier to build in a shop you own. When every process runs in your own code, as one coherent system argues, the order, the consent and the delivery state sit in one database, and the shop can report on itself.

Conclusion

The order table is the truth, and the browser is a sample of it with holes in predictable places. Some holes are the customer's choice, and a server must respect them. The others (blockers, payment detours, closed tabs, short lived cookies) are accidents, and the shop can repair them by reporting purchases itself. To do that, capture the browser's identifiers and the customer's consent at checkout, because the server cannot ask later. Write one outbox row per consented destination when Solidus finalises the order, keyed by the order number, and let a background job deliver, retry and give up honestly. Treat hashed emails as the personal data they are. Let a nightly sweeper check every order has its rows, and alarm against the database, not against a guess. Then the platforms receive every sale they are allowed to see, the same value for the same order, and you find out within hours, not weeks, when that stops being true.

If your analytics and ad platforms see far fewer sales than your shop, book the free workshop: I map where your purchases go missing and what your own database can send, and the first two weeks of work are on me.

Sources

  1. 1.

    WebKit, Tracking Prevention in WebKit (sections on the 7 day cap on script writeable storage and on link decoration), webkit.org, https://webkit.org/tracking-prevention/

  2. 2.

    Google, Measurement Protocol overview, Google Analytics, Google for Developers, checked 22 November 2026, https://developers.google.com/analytics/devguides/collection/protocol/ga4

  3. 3.

    Google, Send Measurement Protocol events to Google Analytics, Google for Developers, checked 22 November 2026, https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag

  4. 4.

    Google, Measurement Protocol reference, Google Analytics, Google for Developers, checked 22 November 2026, https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference

  5. 5.

    Google, Validate Measurement Protocol events, Google for Developers, checked 22 November 2026, https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag

  6. 6.

    Meta, Conversions API: using the API, Meta for Developers, checked 22 November 2026, https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api

  7. 7.

    Meta, Conversions API, server event parameters, Meta for Developers, checked 22 November 2026, https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event

  8. 8.

    Meta, Conversions API, customer information parameters, Meta for Developers, checked 22 November 2026, https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters

  9. 9.

    Google, Upload click conversions, Google Ads API, Google for Developers, checked 22 November 2026, https://developers.google.com/google-ads/api/docs/conversions/upload-clicks

  10. 10.

    Google, Method events.ingest, Data Manager API reference, Google for Developers, checked 22 November 2026, https://developers.google.com/data-manager/api/reference/rest/v1/events/ingest

  11. 11.

    Google, Send Google Ads offline conversions, Data Manager API, Google for Developers, checked 22 November 2026, https://developers.google.com/data-manager/api/devguides/events/google-ads/offline/send-events

  12. 12.

    Google, About importing offline conversions, Google Ads Help, checked 22 November 2026, https://support.google.com/google-ads/answer/7014069?hl=en

  13. 13.

    Google, The Google tag API reference, the get command, Google for Developers, checked 22 November 2026, https://developers.google.com/tag-platform/gtagjs/reference

  14. 14.

    Regulation (EU) 2016/679 (General Data Protection Regulation), Article 7(1), Official Journal of the European Union, EUR Lex, https://eur-lex.europa.eu/eli/reg/2016/679/oj

  15. 15.

    European Communities (Electronic Communications Networks and Services) (Privacy and Electronic Communications) Regulations 2011, S.I. No. 336 of 2011, regulation 5(3) and 5(5), Irish Statute Book, https://www.irishstatutebook.ie/eli/2011/si/336/made/en/print

  16. 16.

    Google, EU user consent policy, Google, checked 22 November 2026, https://www.google.com/about/company/user-consent-policy/

  17. 17.

    Meta, Meta Business Tools Terms, sections 1 and 3, effective 3 November 2025, checked 22 November 2026, https://www.facebook.com/legal/technology_terms

  18. 18.

    European Data Protection Board, Guidelines 01/2025 on Pseudonymisation, version adopted for public consultation on 16 January 2025, executive summary and paragraph 88 with footnote 23, https://www.edpb.europa.eu/system/files/2025-01/edpb_guidelines_202501_pseudonymisation_en.pdf

  19. 19.

    Google, Minimise duplicate key events with transaction IDs, Analytics Help, checked 22 November 2026, https://support.google.com/analytics/answer/12313109?hl=en

  20. 20.

    Meta, Handling duplicate pixel and Conversions API events, Meta for Developers, checked 22 November 2026, https://developers.facebook.com/docs/marketing-api/conversions-api/deduplicate-pixel-and-server-events

  21. 21.

    Chris Richardson, Pattern: Transactional outbox, microservices.io, https://microservices.io/patterns/data/transactional-outbox.html

  22. 22.

    Solidus, source of Spree::Order, method finalize, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/app/models/spree/order.rb

  23. 23.

    Solidus, source of the core engine, the events registered on Spree::Bus, solidus_core on GitHub, main branch, checked 22 November 2026, https://github.com/solidusio/solidus/blob/main/core/lib/spree/core/engine.rb

  24. 24.

    Solidus, Subscribing to events, Solidus Guides, checked 22 November 2026, https://guides.solidus.io/customization/subscribing-to-events

  25. 25.

    Ruby on Rails Guides, Active Job Basics, sections on Solid Queue, transactions and recurring tasks, https://guides.rubyonrails.org/active_job_basics.html

  26. 26.

    Ruby on Rails API, ActiveJob::Exceptions::ClassMethods, retry_on, https://api.rubyonrails.org/classes/ActiveJob/Exceptions/ClassMethods.html