Analytics
Pixelflare counts every image it serves and the bandwidth used, by image, variant, format, country and referrer. That's what the stats dashboard shows you.
Setup
Analytics is on by default through ENABLE_ANALYTICS, and works with no extra setup by writing each image request straight to D1. On a busy site, let the Analytics Engine import fill D1 instead. That saves a D1 write on every request:
# Needed to read traffic back out of Analytics Engine
CLOUDFLARE_ACCOUNT_ID='your-account-id'
CLOUDFLARE_API_TOKEN='your-api-token' # Needs Account Analytics Read
# Optional: configure behaviour
ANALYTICS_REALTIME_ENABLED='false' # Leave D1 to the import (default: true)
ANALYTICS_BATCH_ENABLED='true' # Record traffic in Analytics Engine (default: true)
ANALYTICS_AGGREGATION_CRON='*/15 * * * *' # How often the import runs (default: every 15 minutes)
ANALYTICS_RETENTION_DAYS='400' # How long daily rows are kept (default: 400)Realtime Writes and the Import
The CDN records every image it serves in Analytics Engine. The dashboard reads from D1, though, and there are two ways for requests to get there.
- Realtime on, the default. The CDN also writes each request straight to D1, so today's stats are instant. The import stays idle, so a realtime write that fails isn't made up later.
- Realtime off, with credentials. The CDN makes no analytics writes to D1. Every 15 minutes the import adds the traffic since its last run, about 10 minutes behind. This is the one to use on a busy site.
Switching between the two isn't seamless. When you turn realtime off, the import starts counting from its first run after the deploy, so the few minutes in between don't reach D1, and nothing gets counted twice. Turning it back on drops anything the import hadn't caught up on yet.
With realtime off and no credentials, nothing reaches D1 and the dashboard stays empty. The analytics job logs a warning once a day when it's set up like that.
How It Works
sequenceDiagram
participant User
participant CDN as CDN Route
participant AE as Analytics Engine
participant D1 as D1 Database
participant Job as Analytics Job (every 15 min)
User->>CDN: GET /user/album/file
CDN->>CDN: Serve image from R2
CDN->>AE: Write data point
opt Realtime on
CDN->>D1: Add to analytics_daily
end
CDN-->>User: Return image
opt Realtime off
Job->>AE: Query via the SQL API
AE-->>Job: Traffic, weighted for sampling
Job->>D1: Add the traffic since the last run
end
Job->>D1: Roll finished days into the rollup tables
Note over Job,D1: Plus a daily storage snapshot, and old months trimmed to monthly totalsData Collected
Each image served records:
- Owner. The username of whoever owns the image.
- Image ID. The image that was served.
- Variant. Which size was served, like
original,w1024orthumb. - Requested format. The format it was converted to, like
webporavif, if any. - Country. The ISO country code from Cloudflare's geolocation.
- Referrer. The page the request came from, up to 2048 characters, or
Direct. - Bandwidth. The bytes sent.
Only images that were actually served get counted, so failed requests like 404s don't show up. Pixelflare doesn't store IP addresses or user agents. It does keep referrer URLs, so the dashboard can show where traffic comes from, and those can include query strings.
Storage Schema
Analytics lives in these D1 tables.
analytics_daily. One row per owner, day, image and combination of variant, format, country and referrer. A row with an empty image_id holds the owner's totals for the day, plus a snapshot of their storage.
(owner, date, image_id, variant, requested_format, country, referrer,
requests, bandwidth_bytes, total_images, total_bytes)analytics_monthly. Monthly totals per owner, which outlive the daily rows. A month is added once it's over and the import has finished with its last day.
(owner, year_month, requests, bandwidth_bytes)analytics_daily_dimensions. Per-day totals for each variant, format, country and referrer, so the usage breakdowns read one row per value per day instead of every combination in analytics_daily.
(owner, dimension, date, value, requests, bandwidth_bytes)analytics_daily_images. Per-day totals for each image and variant, for the flows view, sorting images by requests and the request and bandwidth totals in the images table.
(owner, date, image_id, variant, requests, bandwidth_bytes)analytics_meta. How far the analytics job has got, like how far the import has reached and which days are rolled up.
(key, value, updated_at)The two rollup tables cover an unbroken run of finished days. For anything outside that run, like today or days still waiting to be backfilled, the dashboard reads analytics_daily directly, so it never misses a day.
The Analytics Job
The job runs on ANALYTICS_AGGREGATION_CRON, every 15 minutes by default. Each run:
- With realtime off, adds the traffic since the last run. It takes at most
ANALYTICS_IMPORT_MAX_WINDOW_MINUTES(an hour) per run, less if that would be more thanANALYTICS_IMPORT_MAX_ROWSrows, and never runs past midnight in one go. So after a gap it catches up in small steps. - Rolls days the import has finished with into the rollup tables, recent days before backfilling older ones, at most
ANALYTICS_DIMENSION_ROLLUP_MAX_DAYS(two) days per run. Each day can take D1 a second or so, and a run that does too many overloads it, so a backlog catches up slowly. A year of history takes about two days. - Once a day, snapshots each owner's storage. If the snapshot fails, the next run tries it again.
- Rolls the oldest finished month that isn't in
analytics_monthlyyet into it. - Removes daily rows past the retention period, a thousand at a time. See Retention Period.
Each step is separate, so one failing doesn't stop the others, and the job logs every failure. When an import changes a day that's already rolled up, it refreshes that day's rollups in the same transaction, so the two can't disagree.
API Endpoints
All analytics endpoints live under /v1/analytics and need the read scope.
GET /usagereturns totals and daily figures, plus breakdowns by variant, format, country and referrer.GET /images/{id}returns stats for one image, or for up to 100 comma-separated IDs.GET /flowsreturns the busiest images and variants.GET /referrers/timelineandGET /countries/timelinereturn daily figures for the top referrers or countries.GET /usage-limitsreturns current usage against plan limits.
The stats endpoints take days, 30 by default and 90 at most, and offset, which moves the window back to compare with an earlier period. /usage also takes include to pick which breakdowns come back, where an empty value means totals only, and simple=true for daily totals over longer ranges. The API reference has every parameter and response.
Advanced Configuration
Schedule
Change how often the analytics job runs.
ANALYTICS_AGGREGATION_CRON='*/15 * * * *' # Default: every 15 minutesWith realtime off, this sets how fresh today's stats are. A daily schedule works too, but traffic after each run then waits a day to reach D1, and so does the retry for anything that failed.
Retention Period
Control how long D1 keeps daily analytics rows.
ANALYTICS_RETENTION_DAYS='400' # Default: 400 daysOnce a whole month is older than this, the job removes its daily rows and their rollups, leaving its totals in analytics_monthly. It never removes a month before it's there. Each delete takes at most 1,000 rows and a run does at most 6, so a backlog clears over as many runs as it needs, up to about half a million rows a day on the default schedule, rather than in one heavy burst.
The 90-day stats view compares against the 90 days before it, so keep this at 180 or more. Past the retention period, the requests heatmap spreads each month's total evenly across its days.
Disable Analytics
To turn analytics off completely, set this in your deploy config and redeploy.
ENABLE_ANALYTICS='false'It's read when the worker config is generated, which then leaves out the Analytics Engine binding. For a manual deploy, remove the ANALYTICS binding from the worker instead. Images still serve as normal, but nothing gets counted.
Performance Considerations
D1 Load
- Realtime. Two small D1 writes per image request, one for the image's row and one for the owner's totals.
- Import. One small batched write every 15 minutes, with a row per combination of image, variant, format, country and referrer seen since the last run. It stays under
ANALYTICS_IMPORT_MAX_ROWSunless a single minute has more than that, which it imports anyway and logs a warning about. - Dashboard. The usage breakdowns, flows and sorting images by requests read the rollup tables, so they stay quick however busy an account gets. Stats for a single image read just that image's raw rows, through the image index.
Realtime is fine for most sites. On a busy one, I'd turn it off. Serving an image then makes no analytics writes to D1, which leaves D1 to the dashboard and the CDN's own lookups.
Cost
Analytics Engine and D1 each have their own pricing. See the Analytics Engine pricing and D1 pricing pages.
Limitations
- Queries cover 90 days at most, apart from
simpleusage stats - The import needs Cloudflare API credentials
- Analytics Engine keeps data for three months, so the import can't catch up on anything older
- The import reads the
pixflare_cdn_metricsdataset, so keep that dataset name - Countries come from Cloudflare's IP geolocation, which is good but not perfect
- With realtime off, today's figures run about 10 to 25 minutes behind
- Traffic that reaches Analytics Engine more than 10 minutes late isn't imported
Troubleshooting
Dashboard shows no data
- Check the worker has the
ANALYTICSbinding, whichENABLE_ANALYTICSadds when deploying - If
ANALYTICS_REALTIME_ENABLEDisfalse, check the import credentials are set - Check the CDN routes are actually serving images
- With realtime off, wait for the next run
Import fails
- Verify
CLOUDFLARE_ACCOUNT_IDandCLOUDFLARE_API_TOKENare set correctly - Check the API token has the Account Analytics Read permission
- Look in the Worker logs for
Live analytics import failed. The error's cause has the message from Analytics Engine - Ensure the Analytics Engine dataset is named
pixflare_cdn_metrics