Sub topic 11
Checking for data loss with the Data API
This chapter assumes you can read basic Python, have a GA4 property you can query, and know the three mechanisms from the earlier chapters: data thresholds, sampling, and the (other) row. It also assumes you have set up the Google Analytics Data API client library with credentials that can read your property. Setting up credentials is not covered here.
In the GA4 interface you have to notice data loss by eye. A shield icon, a sampling badge, or a row labeled (other) is easy to miss, and none of them appear if you export a table to a spreadsheet. The Data API reports the same problems as fields on every response. You can check those fields in code and stop a pipeline, or flag a dashboard, when a report is incomplete.
Where the flags live
Every run_report response has a metadata object. Three parts of it matter for data loss:
| Field | Type | What it tells you |
|---|---|---|
| `data_loss_from_other_row` | bool | `True` when some dimension combinations were merged into an (other) row because of high cardinality. |
| `subject_to_thresholding` | bool | `True` when the report is subject to data thresholds, so rows below the minimum aggregation level may be withheld. |
| `sampling_metadatas` | list | One entry per date range, present only when the results were sampled. |
Two other places in the response help you check the numbers:
- The
totalsrows, which you get by requestingmetric_aggregations. - The
property_quotaobject, which you get by settingreturn_property_quota=True.
Reading the flags
The first example runs a report and prints the flags. It is the same pattern used in a one-off check.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Dimension, Metric, RunReportRequest
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property="properties/123456789",
dimensions=[Dimension(name="pagePath")],
metrics=[Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="2026-01-01", end_date="2026-01-31")],
)
response = client.run_report(request)
print("Rows returned:", len(response.rows))
print("Data lost to (other) row:", response.metadata.data_loss_from_other_row)
print("Subject to thresholding:", response.metadata.subject_to_thresholding)Replace the property ID with your own. The client reads credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
Interpreting `data_loss_from_other_row`
If this flag is True, the response contains a row whose dimension value is (other). That row holds the metrics of every dimension combination that did not fit. The cause is cardinality: the report has too many unique values for GA4 to return individually. The flag is the API's equivalent of the (other) row you see in the interface.
A False value means no merging occurred in this response. It says nothing about thresholding or sampling, so check those separately.
Interpreting `subject_to_thresholding`
True means the request used a combination of fields and settings that makes GA4 apply data thresholds. It does not mean data was removed. If every row is above the minimum aggregation level, the flag is still True and nothing is missing. Treat it as a warning that rows may be absent, then confirm with the totals check below.
Common reasons for the flag include:
- Requesting demographic or interest dimensions.
- Having Google signals enabled with a reporting identity that uses it.
- Querying small segments of users.
Interpreting `sampling_metadatas`
When results are sampled, the response includes one SamplingMetadata for each date range, in the order you listed the ranges. Each has two numbers:
samples_read_count: how many events GA4 actually read.sampling_space_size: how many events were in the full space it could have read.
Divide the first by the second to get the fraction sampled. If the list is empty, the results were not sampled. Sampling in the Data API is uncommon for ordinary reports, but a pipeline should still test for it, because a field that is silently ignored becomes a silent error.
Checking the totals
The flags describe what GA4 says it did. A second check compares the numbers directly. When you ask for a TOTAL aggregation, GA4 computes it over all the matching data, not only over the rows it returns. If the rows add up to less than the total, rows are missing.
Use an additive metric for this check. eventCount and sessions can be added across rows meaningfully for most dimensions. activeUsers cannot, because one user can appear in many rows, so the sum of rows will exceed the true total even when nothing is missing.
The next script combines all the checks into one function.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
MetricAggregation,
RunReportRequest,
)
def check_report(client, property_id, start_date, end_date, dimension):
request = RunReportRequest(
property=f"properties/{property_id}",
dimensions=[Dimension(name=dimension)],
metrics=[Metric(name="eventCount")],
date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
metric_aggregations=[MetricAggregation.TOTAL],
limit=100000,
return_property_quota=True,
)
response = client.run_report(request)
meta = response.metadata
problems = []
if meta.data_loss_from_other_row:
problems.append("rows were merged into (other)")
if meta.subject_to_thresholding:
problems.append("report is subject to thresholding")
for index, sample in enumerate(meta.sampling_metadatas):
fraction = sample.samples_read_count / sample.sampling_space_size
problems.append(f"date range {index} sampled at {fraction:.1%}")
if response.row_count > len(response.rows):
problems.append(
f"only {len(response.rows)} of {response.row_count} rows returned; paginate"
)
row_sum = sum(int(row.metric_values[0].value) for row in response.rows)
total = int(response.totals[0].metric_values[0].value)
if row_sum < total:
problems.append(f"rows sum to {row_sum} but the total is {total}")
quota = response.property_quota
print("Daily tokens remaining:", quota.tokens_per_day.remaining)
return problems
if __name__ == "__main__":
client = BetaAnalyticsDataClient()
issues = check_report(client, "123456789", "2026-01-01", "2026-01-31", "pagePath")
if issues:
for issue in issues:
print("PROBLEM:", issue)
else:
print("No data loss detected.")Several details in this script matter:
limit=100000raises the page size above the default of 10,000 rows. Without it, a long report is cut off and the row sum falls below the total for a reason unrelated to thresholds.response.row_countis the number of rows the query matched, whilelen(response.rows)is the number returned in this page. If the first is larger, the report is truncated by pagination, not by GA4 withholding data.- Row values arrive as strings, so each is converted with
int. - The totals row is the second source of truth. If the row sum is lower than the total but no flag is
True, look at pagination first.
Telling the causes apart from the output
The combination of results points to a cause. This table summarizes the usual patterns.
| `data_loss_from_other_row` | `subject_to_thresholding` | Row sum vs. total | Likely situation |
|---|---|---|---|
| `True` | `False` | Equal | High-cardinality dimension. Detail is merged into (other). |
| `False` | `True` | Lower | Thresholding withheld rows. |
| `False` | `True` | Equal | Thresholding applies but no row fell below the limit. |
| `False` | `False` | Lower | Check pagination first, then look for a quota or filter issue. |
| `False` | `False` | Equal | No loss detected. |
Sampling shows up separately, through sampling_metadatas, and can combine with any row of the table.
Acting on the result
Once a check fails, change the request, not the interpretation.
- (other) row. Use a dimension with fewer distinct values. For example, query
pagePathwithout query strings by using a page-level dimension, or filter to a smaller part of the site. If you need every value, move to the BigQuery export. - Thresholding. Remove demographic, interest, or other Google signals fields from the request. Ask whoever owns the property whether the reporting identity can use a setting that relies less on Google signals. Widen the date range, because small counts on a single day may clear the minimum over a month.
- Sampling. Shorten the date range, split the request into several smaller date ranges and add the results, or use BigQuery.
- Truncation. Page through the results with the
offsetparameter until you haverow_countrows.
Quota is a separate concern. A data pipeline that issues many requests can exhaust the property's tokens, and the API will then return errors, not partial data. The property_quota object shows how many tokens you have left, so a scheduler can slow down before it hits the limit.
Using the check in a pipeline
You can make this check a gate. Run check_report after each scheduled extraction and fail the job when the list of problems is not empty. Three habits keep this useful:
- Log the flags next to the data. A later reader can then tell which numbers were complete.
- Store the date range and dimension used. The same property can be complete for one dimension and lossy for another.
- Alert on changes, not only on failures. A report that was clean last month and is lossy now often means traffic grew or a setting changed.
Exercise
A Data API report on pagePath returns data_loss_from_other_row = False and subject_to_thresholding = False. The eventCount values in the rows add up to 48,200, but the TOTAL aggregation is 61,750, and row_count is 14,300 while len(response.rows) is 10,000. What is the most likely cause, and what do you change?
Show answer
The report is truncated by pagination. The default page size is 10,000 rows, and the response matched 14,300 rows, so about 4,300 rows were not returned. Neither GA4 flag is set, so thresholding and the (other) row are not the cause. Raise limit (up to 250,000) or page through with offset until you have all row_count rows, then compare the row sum with the total again.
Exercise
Why is activeUsers a poor metric for comparing the sum of rows against the TOTAL aggregation?
Show answer
A single user can appear in several rows, for example by visiting several pages, so the row values add up to more than the number of distinct users. The sum would exceed the total even when no data is missing. Use an additive metric such as eventCount for this check.