> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mavera.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Real-Time Audience → Trending Response

> Pull GA4 real-time active users by page and source, detect traffic spikes against your baseline, and use Mave Agent to diagnose the cause and recommend a response playbook

### Scenario

Traffic just spiked — maybe a tweet went viral, a Product Hunt launch is live, or a competitor's outage is sending visitors your way. You pull GA4's real-time report showing active users by page and traffic source, identify the spike, and send it to Mave for diagnosis and response recommendations. The result is a real-time playbook: what's happening, why, and what to do next.

### Architecture

```mermaid theme={"dark"}
flowchart LR
    A["GA4 RunRealtimeReport (activeUsers × page × source)"] --> B[Detect traffic spike vs baseline] --> C["POST /api/v1/mave/chat"] --> D[Spike diagnosis + response actions]
```

### Code

<CodeGroup>
  ```python Python theme={"dark"}
  import os, requests
  from google.analytics.data_v1beta import BetaAnalyticsDataClient
  from google.analytics.data_v1beta.types import (
      RunRealtimeReportRequest, Dimension, Metric,
  )

  PROPERTY_ID = os.environ["GA4_PROPERTY_ID"]
  MV = os.environ["MAVERA_API_KEY"]

  client = BetaAnalyticsDataClient()

  rt_by_page = client.run_realtime_report(RunRealtimeReportRequest(
      property=f"properties/{PROPERTY_ID}",
      dimensions=[Dimension(name="unifiedPagePathScreen")],
      metrics=[Metric(name="activeUsers")],
      limit=20,
  ))

  rt_by_source = client.run_realtime_report(RunRealtimeReportRequest(
      property=f"properties/{PROPERTY_ID}",
      dimensions=[Dimension(name="sessionSource"), Dimension(name="sessionMedium")],
      metrics=[Metric(name="activeUsers")],
      limit=15,
  ))

  rt_total = client.run_realtime_report(RunRealtimeReportRequest(
      property=f"properties/{PROPERTY_ID}",
      metrics=[Metric(name="activeUsers")],
  ))

  total_active = int(rt_total.rows[0].metric_values[0].value) if rt_total.rows else 0

  page_data = []
  for row in rt_by_page.rows:
      page_data.append({
          "page": row.dimension_values[0].value,
          "active": int(row.metric_values[0].value),
      })

  source_data = []
  for row in rt_by_source.rows:
      source_data.append({
          "source": row.dimension_values[0].value,
          "medium": row.dimension_values[1].value,
          "active": int(row.metric_values[0].value),
      })

  BASELINE_ACTIVE = int(os.environ.get("BASELINE_ACTIVE_USERS", "50"))
  spike_ratio = total_active / max(BASELINE_ACTIVE, 1)

  page_block = "\n".join(f"- {p['page']}: {p['active']} active users" for p in page_data[:10])
  source_block = "\n".join(f"- {s['source']}/{s['medium']}: {s['active']} active" for s in source_data[:10])

  print(f"Total active: {total_active} (baseline: {BASELINE_ACTIVE}, ratio: {spike_ratio:.1f}x)")

  if spike_ratio > 1.5:
      mave = requests.post(
          "https://app.mavera.io/api/v1/mave/chat",
          headers={"Authorization": f"Bearer {MV}", "Content-Type": "application/json"},
          json={"message": f"""We're seeing a traffic spike on our website. Diagnose and recommend a response.

  REAL-TIME DATA:
  - Total active users: {total_active} (normal baseline: {BASELINE_ACTIVE}, this is {spike_ratio:.1f}x normal)

  TOP PAGES BY ACTIVE USERS:
  {page_block}

  TRAFFIC SOURCES:
  {source_block}

  Analyze:
  1. What's likely driving this spike? (based on page + source patterns)
  2. Is this an opportunity or a threat? (e.g. viral content vs competitor outage vs bot traffic)
  3. Immediate actions (next 30 minutes)
  4. Follow-up actions (next 24 hours)
  5. Content to publish or promote RIGHT NOW to capitalize
  6. If this is from a specific source (e.g. social, referral), what's the engagement playbook?"""},
      ).json()

      print("\n--- Spike Analysis ---")
      print(mave.get("content", "")[:2500])
  else:
      print("No significant spike detected. Run this script when traffic exceeds 1.5x baseline.")
  ```

  ```javascript JavaScript theme={"dark"}
  const MV = process.env.MAVERA_API_KEY;
  const PROPERTY_ID = process.env.GA4_PROPERTY_ID;
  const KEY_FILE = JSON.parse(require("fs").readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, "utf8"));
  const BASELINE = parseInt(process.env.BASELINE_ACTIVE_USERS || "50");

  const { GoogleAuth } = require("google-auth-library");
  const auth = new GoogleAuth({
    credentials: KEY_FILE,
    scopes: ["https://www.googleapis.com/auth/analytics.readonly"],
  });
  const accessToken = await auth.getAccessToken();

  async function realtimeReport(body) {
    return fetch(
      `https://analyticsdata.googleapis.com/v1beta/properties/${PROPERTY_ID}:runRealtimeReport`,
      {
        method: "POST",
        headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
        body: JSON.stringify(body),
      }
    ).then((r) => r.json());
  }

  const [rtPages, rtSources, rtTotal] = await Promise.all([
    realtimeReport({
      dimensions: [{ name: "unifiedPagePathScreen" }],
      metrics: [{ name: "activeUsers" }],
      limit: 20,
    }),
    realtimeReport({
      dimensions: [{ name: "sessionSource" }, { name: "sessionMedium" }],
      metrics: [{ name: "activeUsers" }],
      limit: 15,
    }),
    realtimeReport({ metrics: [{ name: "activeUsers" }] }),
  ]);

  const totalActive = parseInt(rtTotal.rows?.[0]?.metricValues?.[0]?.value || "0");
  const spikeRatio = totalActive / (BASELINE || 1);

  const pageData = (rtPages.rows || []).map((r) => ({
    page: r.dimensionValues[0].value,
    active: parseInt(r.metricValues[0].value),
  }));
  const sourceData = (rtSources.rows || []).map((r) => ({
    source: r.dimensionValues[0].value,
    medium: r.dimensionValues[1].value,
    active: parseInt(r.metricValues[0].value),
  }));

  console.log(`Active: ${totalActive} (baseline: ${BASELINE}, ${spikeRatio.toFixed(1)}x)`);

  if (spikeRatio > 1.5) {
    const pageBlock = pageData.slice(0, 10).map((p) => `- ${p.page}: ${p.active} active`).join("\n");
    const sourceBlock = sourceData.slice(0, 10).map((s) => `- ${s.source}/${s.medium}: ${s.active} active`).join("\n");

    const mave = await fetch("https://app.mavera.io/api/v1/mave/chat", {
      method: "POST",
      headers: { Authorization: `Bearer ${MV}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        message: `Traffic spike detected: ${totalActive} active (${spikeRatio.toFixed(1)}x normal).\n\nTOP PAGES:\n${pageBlock}\n\nSOURCES:\n${sourceBlock}\n\nDiagnose: 1) What's driving it? 2) Opportunity or threat? 3) Immediate actions 4) 24h follow-up 5) Content to publish now 6) Engagement playbook`,
      }),
    }).then((r) => r.json());

    console.log("\n--- Spike Analysis ---");
    console.log((mave.content || "").slice(0, 2500));
  } else {
    console.log("No significant spike. Run when traffic exceeds 1.5x baseline.");
  }
  ```
</CodeGroup>

### Example Output

```text theme={"dark"}
Active: 342 (baseline: 50, 6.8x)

--- Spike Analysis ---

## Diagnosis
Traffic is concentrated on /blog/ai-marketing-2026 (189 active users) with
the primary source being twitter/social (201 active). This pattern indicates
a viral social share — likely a tweet linking to your blog post.

## Assessment: OPPORTUNITY
This is organic amplification. The blog post is resonating. No bot indicators
(diverse pages getting traffic, source is identifiable social media).

## Immediate Actions (Next 30 Minutes)
1. **Pin a reply** to the viral tweet with a CTA to your product
2. **Add an exit-intent popup** on the blog post with a lead magnet
3. **Publish a follow-up tweet thread** expanding on the blog's key points
4. **Alert sales** — any leads from this page in the last hour get priority

## Follow-Up (Next 24 Hours)
1. Publish a Part 2 blog post while attention is high
2. Create a LinkedIn post repurposing the blog's key insight
3. Email your list with the blog post as featured content
4. Build a retargeting audience from today's visitors
```

### Error Handling

<AccordionGroup>
  <Accordion title="Real-time data is approximate">GA4 real-time reports show data from the last 30 minutes with \~1-minute latency. Numbers are approximate and may differ from standard reports.</Accordion>
  <Accordion title="Baseline calibration">Set `BASELINE_ACTIVE_USERS` to your typical real-time user count. Check GA4 → Reports → Real-time during normal hours to establish this.</Accordion>
  <Accordion title="Rate limits on real-time reports">Real-time reports count against the same 10 concurrent / 50,000 daily quota. Don't poll more frequently than every 60 seconds.</Accordion>
</AccordionGroup>

***

## What's Next

<CardGroup cols={2}>
  <Card title="GA4 Integration" icon="chart-line" href="/integrations/ga4">
    Back to GA4 integration overview
  </Card>

  <Card title="Landing Page Performance → Content Refresh" icon="wand-magic-sparkles" href="/integrations/ga4/landing-page-refresh">
    Rewrite underperforming landing page copy
  </Card>

  <Card title="Acquisition Channel × Persona Mapping" icon="users" href="/integrations/ga4/channel-persona-mapping">
    Map channel-demographic pairs to personas
  </Card>

  <Card title="Mave Agent" icon="brain" href="/api-reference/mave">
    Full reference for POST /api/v1/mave/chat
  </Card>
</CardGroup>
